如何使用 Mockito 和 Junit 模拟 ZonedDateTime

Som*_*Som 7 java mockito

我需要模拟一个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;
    }
    
}
Run Code Online (Sandbox Code Playgroud)

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

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

我想ZonedDateTime.ofInstant()模拟在解析负面场景时抛出 DateTimeException 的方法。我怎样才能做到这一点。

Hec*_*orC 11

截至目前(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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-inline</artifactId>
        <version>4.4.0</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)


Edu*_*eda 4

您不能使用Mockito它,因为ZonedDateTime它是最终类并且ofInstant静态方法,但您可以使用该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()));
Run Code Online (Sandbox Code Playgroud)

  • 当前版本的 Mockito 也支持模拟静态。 (4认同)