1

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 ?

sr123
  • 85
  • 1
  • 11
  • Consider inverting dependencies if possible: you can have a package-private constructor that accepts a supplier that returns `LocalDateTime` thus can be mocked easily (therefore the unit uses `localDateTimeSupplier.get()` where you have `LocalDateTime.now()` currently). Now your unit does not seem to have it, so it looks like your tests must know really much about unit internals in order to make unit test work. Mocking static methods, especially those that are not exposed from the unit, may be a very wrong way to go. – terrorrussia-keeps-killing Apr 12 '21 at 15:42
  • https://www.baeldung.com/java-override-system-time – Eritrean Apr 12 '21 at 15:52
  • FYI: [`Clock.fixed`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Clock.html#fixed(java.time.Instant,java.time.ZoneId)) – Basil Bourque Apr 12 '21 at 20:35

1 Answers1

5

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.

mrts
  • 16,697
  • 8
  • 89
  • 72
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 1
    @mrts How is `LocalDateTime` the same as `java.lang.System` ? – Yassin Hajaj Jan 20 '22 at 11:32
  • 1
    Apologies, `java.lang.Date` was in my mental context and I just saw it instead of `LocalDateTime`. _You only see what you want to see_, as Madonna sings... `Date` constructor uses `System.currentTimeMillis()` internally. I'll remove the misleading comment. – mrts Jan 20 '22 at 16:46
  • 1
    @mrts No problem, thanks :) – Yassin Hajaj Jan 21 '22 at 06:50