我需要测试一个函数,其结果将取决于当前时间(使用Joda时间isBeforeNow()).
public boolean isAvailable() {
return (this.someDate.isBeforeNow());
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用Mockito存根/模拟系统时间,以便我可以可靠地测试功能?
java.time有一个Instant类,它封装了时间轴上的位置(或"时刻").虽然我知道这是秒/纳秒值,因此与时区或时间偏移没有直接关系,但它toString返回格式为UTC日期/时间的日期和时间,例如2014-05-13T20:05:08.556Z.此外anInstant.atZone(zone),anInstant.atOffset(offset)两者都产生一个值,该值与将Instant具有隐含的UTC时区/"零"偏移量视为一致.
因此我原以为:
ZoneOffset.from(anInstant) 产生'零' ZoneOffset OffsetDateTime.from(anInstant) 产生一个'零'偏移的日期/时间ZoneId.from(anInstant) (可能)生成UTC ZoneId ZonedDateTime.from(anInstant)(可能)ZonedDateTime用UTC 生成一个ZoneIdZonedDateTime.from正如我所读到的那样,该文件似乎赞同这一点.
事实上ZoneOffset.from(anInstant)失败了DateTimeException,我想因为这个原因OffsetDateTime.from(anInstant)也失败了,其他两个也失败了.
这是预期的行为吗?
我需要在 Java 8 中模拟时间(到特定日期,这意味着我可能不会使用anyLong())以java.time在 EasyMock 下的测试环境中单独使用,因此没有 Joda Time。
EasyMock 不允许你模拟像LocalDateTime.now(). PowerMock 可以,但我不允许使用 PowerMock。
Joda Time 库提供了一种简洁优雅的方式来模拟时间DateTimeUtils.setCurrentMillisFixed(),并DateTimeUtils.setCurrentMillisSystem()回到现在的瞬间。
只有我不允许使用 Joda Time。
我被告知使用模拟时钟java.time.Clock类实例并将其注入LocalDateTime.now()如下:LocalDateTime.now(mockClock)
有没有办法在没有 Joda Time和 PowerMock 的情况下正确实现它?