我正在尝试为我正在处理的项目中的一些实用程序类设置单元测试,其中一个类(包含许可信息)具有一种基于当前时间进行某些确定的方法.
I'm taking a stab at setting up unit tests for some utility classes in a project I'm working on, and one of the classes (contains licensing info) has a method that does some determination based on the current time.
即许可证包含到期日期,并且许可证字符串验证该日期,但查看许可证是否过期的实际逻辑是基于当前时间.
i.e. the license contains an expiry date, and the license string validates that date, but the actual logic to see if the license is expired is based on the current time.
public boolean isValid()
{
return isLicenseStringValid() && !isExpired();
}
public boolean isExpired()
{
Date expiry = getExpiryDate();
if( expiry == null ) {
return false;
}
Date now = new Date();
return now.after( expiry );
}
所以,我不确定该怎么做,因为new Date()"不是静态标准.
So, I'm not sure what to do, since the 'new Date()' thing isn't a static criterion.
其他人通常如何处理时间条件测试?
What do others normally do with tests that are time-conditional?
一定要mock out new Date()
.
Definitely mock out new Date()
.
使用 getCurrentTime()
方法或类似方法创建一个 Clock
接口.这样你就可以有一个 FakeClock
用于测试和一个 SystemClock
使用 System.currentTimeMillis()
或其他.
Create a Clock
interface with a getCurrentTime()
method or something similar. That way you can have a FakeClock
for testing and a SystemClock
which uses System.currentTimeMillis()
or whatever.
我已经做过很多次了——效果非常好.这也是合乎逻辑的——实际上你需要一个当前时间服务",所以它应该像任何其他依赖项一样被注入.
I've done this a number of times - it's worked extremely well. It's logical too - effectively you require a "current time service" so that should be injected like any other dependency.
这篇关于处理具有当前时间条件的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!