Imagine we have the following class that I would like to test:
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;
}
}
How can I force the date to be in November and assert that the method returns 2?
I am using JUnit and Mockito.
Assuming there is a setter for the Clock object in Times class, you can do something like this:
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());
In this code, a fixed clock is created. This simulates a constant time for the given instant, that is in November.
As such, any call to LocalDate.now(clock) will always return the same date in November.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With