LocalDateTime.of 返回 null

Ada*_*lle -1 java datetime mockito java-time powermockito

我正在尝试对使用java.time.LocalDateTime. 我能够让模拟工作,但是当我增加时间(分钟或天)时,我最终会得到一个null值。

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白(我想我明白)这LocalDateTime是不可变的,我认为我应该得到一个新实例而不是null值。

原来是.of方法给了我一个null价值。为什么?

And*_*eas 5

根据文档

使用PowerMock.mockStatic(ClassThatContainsStaticMethod.class)嘲笑所有此类的方法。

和:

请注意,即使类是最终的,您也可以模拟类中的静态方法。该方法也可以是最终的。嘲笑一类的仅特定静态方法指局部嘲笑的文件中。

要模拟系统类中的静态方法,您需要遵循这种方法。

您告诉它模拟所有静态方法,但没有为该of()方法提供模拟。

解决方法:要么为of()方法添加mock,要么改用partial mocking,这样of()方法就不会被mock了。

基本上,阅读并遵循文档的说明