繁体   English   中英

我怎样才能让 DateUtil 抛出异常?

[英]How can i make DateUtil throw an exception?


    @Override
        public void contextDestroyed(ServletContextEvent sce) {
            try{
                DateUtil.clean();
            }catch(Exception e){
                LOGGER.error("MyServletContextListener contextDestroyed error: ", e);
            }

我正在对上面的代码进行单元测试,并试图通过点击 Exception 子句来获得 100% 的行覆盖率,但是,我似乎无法让它与我的实现一起工作。 将不胜感激任何帮助。 请在下面查看我的实现。

 @Test (expected= Exception.class)
    public void test_contextDestroyed_Exception() {

        DateUtil wrapper = Mockito.spy(new DateUtil());
        Exception e = mock(Exception.class);

        when(wrapper).thenThrow(e);
       Mockito.doThrow(e)
                .when(myServletContextListener)
                .contextDestroyed(sce);

        myServletContextListener.contextDestroyed(sce);
    } 

由于DateUtil.clean()是一个 static 方法,因此不能用 Mockito 模拟它。 您需要改用 PowerMockito:

<properties>
    <powermock.version>1.6.6</powermock.version>
</properties>
<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
</dependencies>

检查官方 PowerMock 文档以了解与 JUnit 和 Mockito 的版本兼容性。

一旦你这样做了,你应该在你的测试 class 中添加以下内容:

@RunWith(PowerMockRunner.class) //<-- this says to JUnit to use power mock runner
@PrepareForTest(DateUtil.class) //<-- this prepares the static class for mock
public class YourTestClass {
    
    @Test(expected = Exception.class)
    public void test_contextDestroyed_Exception() {
        PowerMockito.mockStatic(DateUtil.class);
        when(DateUtil.clean()).thenThrow(new Exception("whatever you want"));
        //prepare your test
        //run your test:
        myServletContextListener.contextDestroyed(sce);
    }
    
 
}

您可以使用来自 Mockito 的mockito-inline工件来测试 static 方法并遵循以下方法,

try (MockedStatic<DateUtil> utilities = Mockito.mockStatic(DateUtil.class)) {
            utilities.when(DateUtil::clean).thenThrow(Exception.class);
            // assert exception here
        }

欲了解更多信息,

https://frontbackend.com/java/how-to-mock-static-methods-with-mockito

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM