How to mock LocalDateTime.now() in java 8

Tags: , , , ,



Please,

I am testing a functionality ABC that uses LocalDateTime.now().

In the methode ABC i’am comparing an entry date with the LocalDateTime.now()

I want my test to be passed at any day so i have to mock the LocalDateTime.now()

This is my test:

public void testClass() {

       LocalDateTime mock = Mockito.mock(LocalDateTime.class);
       Mockito.doReturn(LocalDateTime.of(2030,01,01,22,22,22)).when(mock).now();

      log.info(String.valueOf(LocalDateTime.now()));

       myService.ABC();
}  

I am using JAVA 8

the date shown in the console is always the real LacalDateTime not my wanted LacalDateTime (2030-01-01) .

I am not getting errors.

Any help please ?

Answer

You should use Mockito#mockStatic for this use case

You can use it like this

try(MockedStatic<LocalDateTime> mock = Mockito.mockStatic(LocalDateTime.class, Mockito.CALLS_REAL_METHODS)) {
    doReturn(LocalDateTime.of(2030,01,01,22,22,22)).when(mock).now();
    // Put the execution of the test inside of the try, otherwise it won't work
}

Notice the usage of Mockito.CALLS_REAL_METHODS which will guarantee that whenever LocalDateTime is invoked with another method, it will execute the real method of the class



Source: stackoverflow