Search code examples
javadatetimemockitojava-timepowermockito

LocalDateTime.of returns null


I am trying to Unit test code that uses java.time.LocalDateTime. I'm able to get the mock working, however when I add time (either minutes or days) I end up with a null value.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocalDateTime.class })
public class LocalDateTimeMockTest
{
    @Test
    public void shouldCorrectlyCalculateTimeout()
    {
        // arrange
        PowerMockito.mockStatic(LocalDateTime.class);
        LocalDateTime fixedPointInTime = LocalDateTime.of(2017, 9, 11, 21, 28, 47);
        BDDMockito.given(LocalDateTime.now()).willReturn(fixedPointInTime);

        // act
        LocalDateTime fixedTomorrow = LocalDateTime.now().plusDays(1); //shouldn't this have a NPE?

        // assert
        Assert.assertTrue(LocalDateTime.now() == fixedPointInTime); //Edit - both are Null
        Assert.assertNotNull(fixedTomorrow); //Test fails here
        Assert.assertEquals(12, fixedTomorrow.getDayOfMonth());
    }
}

I understand (well I think I do) that LocalDateTime is immutable, and I would think I should get a new instance instead of the null value.

Turns out it is the .of method that is giving me a null value. Why?


Solution

  • According to the documentation:

    Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.

    and:

    Note that you can mock static methods in a class even though the class is final. The method can also be final. To mock only specific static methods of a class refer to the partial mocking section in the documentation.

    To mock a static method in a system class you need to follow this approach.

    You told it to mock all the static methods, but didn't supply a mock for the of() method.

    Solution: Either add mock for the of() method, or change to use partial mocking, so the of() method is not mocked.

    Basically, read and follow the instructions of the documentation.