0

I'd like to mock both LocalDate.now() and LocalDateTime.now() in unitTest. However, it seems the first LocalDateTime mock somehow doesn't work correctly if both are present.

@Test
void someTest(){
// create a fixed current date for testing
LocalDateTime fixedCurrentDate = LocalDateTime.of(2023, 3, 1, 0 ,0, 0);

        // initialize the mock of the static method
        MockedStatic<LocalDateTime> mockLocalDateTime = mockStatic(LocalDateTime.class, Mockito.CALLS_REAL_METHODS);
        MockedStatic<LocalDate> mockLocalDate = mockStatic(LocalDate.class, Mockito.CALLS_REAL_METHODS);
    
        // define the behaviour of the mock
        mockLocalDateTime.when(LocalDateTime::now).thenReturn(fixedCurrentDate);
        mockLocalDate.when(LocalDate::now).thenReturn(fixedCurrentDate.toLocalDate());
}

Error:

LocalDateTime cannot be returned by ofEpochDay()
ofEpochDay() should return LocalDate

If I only mock either of them, it works. what went wrong here?

Wolp2a
  • 1
  • 4
    I wouldn't bother mocking any of them. Use a `Clock` and pass it to each of the `now` methods. Use a fixed clock for reproducible tests and the system clock for production. – Ole V.V. Mar 05 '23 at 14:51
  • See the related and similar question: [How to test date created with LocalDateTime.now()](https://stackoverflow.com/questions/39527752/how-to-test-date-created-with-localdatetime-now) – Ole V.V. Mar 05 '23 at 19:36

0 Answers0