Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit with Java 8 Clock

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.

like image 768
Michał Wolnicki Avatar asked Mar 06 '26 21:03

Michał Wolnicki


1 Answers

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.

like image 180
Tunaki Avatar answered Mar 09 '26 10:03

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!