[英]How to unit test a time dependent method with JUnit
我有以下方法,该方法采用UNIX时间戳,并以天,小时或分钟为单位返回使用期限。 我想用JUnit对其进行单元测试,但是由于当前时间不断变化,我不确定如何开始这样做。 有什么建议吗? 谢谢!
方法如下:
public static String getAge(long unixTime) throws Exception {
long diff = (System.currentTimeMillis() / 1000) - unixTime;
diff = diff / 60;
if (diff < 60) {
return Math.round(diff) + " m";
}
else
diff /= 60;
if (diff < 24) {
return Math.round(diff) + " h";
}
else {
diff /= 24;
return Math.round(diff) + " d";
}
}
您应该更改方法的设计以同时接受当前时间和unixTime,或者必须退出纯JUnit并使用PowerMock来模拟System.currentTimeMillis()以返回所需的结果。
我会根据当前时间在unitTest中建立一个unix时间戳。 该方法的结果的粒度足够粗糙,以至于您创建参数和执行此方法之间的时间差只有几毫秒。 当然,您需要避免使用边界条件,即在60分钟和24小时的unixTime。
public void testMinutes() {
Instant minutesAgo = Instant.ofEpochMilli(System.currentTimeMillis() - 15 * 60 * 1000);
String result = getAge(minutesAgo.getEpochSecond());
assertSomething...
}
如此进行数小时和数天的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.