微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何让 DateUtil 抛出异常?

如何解决如何让 DateUtil 抛出异常?


    @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() 是一个静态方法,你不能用 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>

检查 official PowerMock documentation 以了解与 JUnit 和 Mockito 的版本兼容性。

完成后,您应该将以下内容添加到您的测试类中:

@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 工件来测试静态方法并遵循以下方法,

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。