簡體   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