I referred to this answer How can I mock java.time.LocalDate.now() on how to mock my LocalDateTime.now() call. I essentially followed all the steps but just used LocalDateTime instead of LocalDate.
The functionality of my code is such that is should only run at the 15th or 45th minute of the hour. Thus I set my LOCAL_DATE_TIME static variable to the following:
private final static LocalDateTime LOCAL_DATE_TIME = LocalDateTime.of(2019,10,15,19,15,22);
Then in my @Before test method, I have the following :
@Mock
private Clock clock;
private Clock fixedClock;
private final static LocalDateTime LOCAL_DATE_TIME = LocalDateTime.of(2019,10,15,19,15,22);
This is 2019-10-15T19:15:22.
@Before
public void before(){
fixedClock = Clock.fixed(LOCAL_DATE_TIME.toLocalDate().atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());
doReturn(fixedClock.instant()).when(clock).instant();
doReturn(fixedClock.getZone()).when(clock).getZone();
}
This is the code that I'm testing
@Override
public void punctuate(long l) {
LocalDateTime localDateTime = LocalDateTime.now(clock);
int currentMinute = localDateTime.getMinute();
if(currentMinute == 15 || currentMinute == 45) { ....
When I place a breakpoint on the first line above, I see that localDateTime is set to 2019-10-15T00:00
So it looks like the date is being mocked fine, however I'm unable to mock the time. What should I do to mock the minute value?
Converting to LocalDate
will remove the time part of your LocalDateTime
, so don't do that.
Initialize your fixedClock
like this:
fixedClock = Clock.fixed(
LOCAL_DATE_TIME.atZone(ZoneId.systemDefault()).toInstant(),
ZoneId.systemDefault()
);