我想單元測試使用java.time.LocalDateTime
的代碼。我能夠得到模擬工作,但是當我添加時間(無論是分鐘還是天)時,我最終得到的值爲null
。LocalDateTime.of返回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());
}
}
我明白(嗯,我想我這樣做)是LocalDateTime
是不可改變的,而且我認爲我應該得到一個新的實例,而不是null
值。
原來,這是.of
方法,它給了我一個null
值。爲什麼?
您是否嘗試運行代碼沒有嘲笑? powermockito很有可能造成這個問題。 – Ali
並考慮重新考慮使用PowerMock(ito);-) – GhostCat
當嘲笑一個Java「系統」類(如'java.time.LocalDateTime')時,PowerMock要求非系統類*使用*該類在'@ PrepareForTest'中列出(正如其他答案中已經指出的那樣)。但根據我的經驗,像這樣的測試中最大的錯誤是甚至會引起嘲笑日期/時間戳或系統時鐘的想法。如果SUT使用'LocalDateTime.now()',那麼它很可能應該允許從外部(通過調用者代碼)給出一個日期對象,這將使得編寫測試時沒有任何嘲諷的微不足道。去過也做過。 –