是否可以冻结 System.currentTimeMillis() 进行测试 [英] Is it possible to freeze System.currentTimeMillis() for testing

查看:38
本文介绍了是否可以冻结 System.currentTimeMillis() 进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某些测试目的,我想准确预测 System.currentTimeMillis() 将返回什么.有什么方法可以冻结或手动设置调用 System.currentTimeMillis() 时返回的内容?

For some testing purposes I would like to predict exactly what System.currentTimeMillis() will return. Is there any way in which I can freeze or manually set what will return when System.currentTimeMillis() is called?

推荐答案

我强烈建议您避免使用 System.currentTimeMillis(和 new Date() 等)在您的通用代码中.

I would strongly suggest that you avoid using System.currentTimeMillis (and new Date() etc) in your general code.

相反,创建一个 Clock 接口表示提供当前时间的服务",然后创建一个确实使用 System.currentTimeMillis 的实现code> 或其他任何东西,以及您可以明确控制的虚假实现.

Instead, create a Clock interface representing "a service to give you the current time" and then create one implementation which does use System.currentTimeMillis or whatever, and a fake implementation that you can control explicitly.

使用依赖注入使需要它的代码可以使用此服务的实例.在生产中,使用 System.currentTimeMillis 版本,并在测试中使用你的假.

Use dependency injection to make an instance of this service available to code which needs it. In production, use the System.currentTimeMillis version, and in testing use your fake.

这不仅使您能够停止时间,还可以将其设置为您想要的任何值 - 这样您就可以拥有永不过期的静态测试数据,并且您可以轻松地测试边界等棘手的事情.我'我在很多项目中都非常成功地使用了这种方法,以至于在我的 Noda Time 项目中,它是获取当前时间"的方式.

This gives you the ability not just to stop time, but to set it to whatever you want - so you can have static test data which you know will never expire, and you can easily test tricky things around boundaries etc. I've used this approach very successfully in many projects, to the extent that in my Noda Time project it's the way of getting at "the current time".

请注意,如果您使用 Java 进行大量时间工作,我建议您使用 Joda Time,并且让你的 Clock 接口返回一个 Instant:

Note that if you're doing any serious amount of time work in Java, I'd recommend using Joda Time, and making your Clock interface return an Instant:

public interface Clock {
    Instant now();
}

这篇关于是否可以冻结 System.currentTimeMillis() 进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆