javajava-time

Mocking LocalDate.now() but when using plusDays it returns null?


In my code I need to use LocalDate.now(), then I work out an estimated date from today by using the plusDays(num).

In my unit test, when I mock the static .now() method, when it calls the plusDays() method the output is null.

Any Ideas?

Code

LocalDate today = LocalDate.now();
int estimatedDays = fullPeriod - countSoFar;
LocalDate estimatedDate  = today.plusDays(estimatedDays);

Test

try(MockedStatic<LocalDate> mockedLocalDate = Mockito.mockStatic(LocalDate.class)) {
            mockedLocalDate.when(LocalDate::now).thenReturn(startDate);

            String actual = generator.generateCsv("text", "text", startDate, endDate);

            String expected = "Some text containing {Estimated Date}";
            assertEquals(expected, actual);
}

Edit: enter image description here

When I mock the LocalDate it looks normal in the call to LocalDate.now() but when it goes into the plusDay() method it returns null

Inside the Math function r is not null at this point but as soon as it comes out this method the resultant variable is?

enter image description here


Solution

  • java.time.Clock

    Instead of mocking a static method (which in my opinion is never a good idea) you can use the Clock feature offered by the java.time API. You can pass an instance of java.time.Clock, a fixed clock for example.

    From the Clock JavaDoc:

    Best practice for applications is to pass a Clock into any method that requires the current instant. A dependency injection framework is one way to achieve this:

    public class MyBean {
     private Clock clock;  // dependency inject
     ...
     public void process(LocalDate eventDate) {
       if (eventDate.isBefore(LocalDate.now(clock)) {
         ...
       }
     }
    }   
    

    This approach allows an alternate clock, such as fixed or offset to be used during testing.