如何使用 Mockito 和 Junit 模拟 ZonedDateTime

How to Mock a ZonedDateTime with Mockito and Junit

我需要模拟一个 ZonedDateTime.ofInstant() 方法。我知道 SO 中有很多建议,但是对于我的具体问题,到目前为止我还没有找到任何简单的出路。

这是我的代码:

public ZonedDateTime myMethodToTest(){

    MyClass myClass;
    myClass = fetchSomethingFromDB();
    try{
        final ZoneId systemDefault = ZoneId.systemDefault();
        return ZonedDateTime.ofInstant(myClass.getEndDt().toInstant(), systemDefault);
    } catch(DateTimeException dte) {
        return null;
    }
    
}

这是我不完整的测试方法:

 @Mock
 MyClass mockMyClass;

 @Test(expected = DateTimeException.class)
 public void testmyMethodToTest_Exception() {
    String error = "Error while parsing the effective end date";
    doThrow(new DateTimeException(error)).when(--need to mock here---);
    ZonedDateTime dateTime = mockMyClass.myMethodTotest();
}

我想模拟 ZonedDateTime.ofInstant() 方法以在解析负面情况时抛出 DateTimeException。我该怎么做。

您不能为此使用 Mockito,因为 ZonedDateTime 是最终的 class 而 ofInstantstatic 方法,但您可以使用 PowerMock 库来增强 Mockito 功能:

final String error = "Error while parsing the effective end date";
// Enable static mocking for all methods of a class
mockStatic(ZonedDateTime.class);
PowerMockito.doThrow(new DateTimeException(error).when(ZonedDateTime.ofInstant(Mockito.anyObject(), Mockito.anyObject()));

截至目前(18/03/2022)Mockito 支持模拟静态方法。你可以做到

@Test
public void testDate() {
    String instantExpected = "2022-03-14T09:33:52Z";
    ZonedDateTime zonedDateTime = ZonedDateTime.parse(instantExpected);

    try (MockedStatic<ZonedDateTime> mockedLocalDateTime = Mockito.mockStatic(ZonedDateTime.class)) {
        mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime);

        assertThat(yourService.getCurrentDate()).isEqualTo(zonedDateTime);
    }
}

请注意,您需要使用mockito-inline依赖:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-inline</artifactId>
        <version>4.4.0</version>
    </dependency>