Rob
Rob

Reputation: 75

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

Upvotes: 2

Views: 3114

Answers (2)

Evoltafreak
Evoltafreak

Reputation: 528

Did you try to add Mockito.CALLS_REAL_METHODS to your mockStatic method? Your code would look something like this:

try (MockedStatic<LocalDate> mockedLocalDate = Mockito.mockStatic(LocalDate.class, Mockito.CALLS_REAL_METHODS)) {
            mockedLocalDate.when(LocalDate::now).thenReturn(startDate);
            String actual = generator.generateCsv("text", "text", startDate, endDate);
            String expected = "Some text containing {Estimated Date}";
            assertEquals(expected, actual);
}

Upvotes: 2

Adriaan Koster
Adriaan Koster

Reputation: 16209

java.time.Clock

Instead of mocking a static method (which is never a good idea really IMO) you can use the Clock feature offered by the java.time API itself. 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.

Upvotes: 3

Related Questions