Mic*_*cki 3 java junit java-8 java-time
想象一下,我想要测试以下课程:
class Times {
Clock cl = Clock.systemDefaultZone();
public int changeTime() {
LocalDate ld = LocalDate.now(cl);
if(ld.getMonth().equals(Month.OCTOBER))
return 1;
if(ld.getMonth().equals(Month.NOVEMBER))
return 2;
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
如何强制日期在11月并断言该方法返回2?
我正在使用JUnit和Mockito.
假设Clock在Times类中有对象的setter ,你可以这样做:
Times times = new Times();
Clock fixedClockInNovember = Clock.fixed(Instant.parse("2015-11-01T00:00:00.00Z"), ZoneId.of("UTC"));
times.setClock(fixedClockInNovember);
assertEquals(2, times.changeTime());
Run Code Online (Sandbox Code Playgroud)
在此代码中,创建固定时钟.这模拟了给定时刻的恒定时间,即11月.
因此,任何电话LocalDate.now(clock)会在11月返回相同的日期.