簡體   English   中英

如何使用 mockito / powermockito 使實例化的依賴 class 在特定方法調用上引發異常

[英]How to use mockito / powermockito to make an instantiated dependent class throw an exception on a specific method call

這是我要測試的代碼。 這很簡單

  class FileHandler {
    public boolean deleteFiles(String path) {
      // mock this to throw an exception
    }
    public static FileHandler instatiateNew(String location) {
      // creates a FileHandler
    }
  }

  class B {
    public void action {
      try {
        FileHandler x = FileHandler.instantiateNew("asd");
        x.deleteFiles();
      } catch (Exception e) {
        // untested code I want to reach
      }
    }
  }

我現在想測試方法action ,看看它如何處理 x.deleteFiles() 拋出異常。 我試過doThrow,thenThrow並遇到錯誤(NullPointerException,可能是因為我錯誤地存根方法)或者方法最終沒有拋出異常。

我也很困惑是否需要 Powermockito。 我現在將嘗試一種方法,在其中模擬整個 FileHandler class。 因為我需要模擬 static 實例化方法,所以我需要 PowerMock。 但我更喜歡不那么笨拙的解決方案。 它存在嗎?

我的部分 class 模擬現在是:

FileHandler mockHandler = Mockito.mock(FileHandler.class)
Mockito.mock(mockHandler.deleteFiles(Mockito.anyString()).thenThrow(Exception.class);
PowerMockito.mockStatic(FileHandler.class);
PowerMockito.when(FileHandler.instantiateNew(Mockito.anyString())).thenReturn(mockHandler())

這仍然會導致問題,可能是因為 FileHandler 在其他地方使用,而 mockStatic 會殺死所有其他用法。

確保正確安排所有必要的成員,以便可以進行測試。

例如

RunWith(PowerMockRunner.class)
@PrepareForTest({FileHandler.class})
public class MyTestCase {
    public void testdeleteFilesErrorHandling() throws Exception {
        //Arrange
        //instance mock
        FileHandler handler = Mockito.mock(FileHandler.class);
        Mockito.when(handler.deleteFiles(anyString())).thenThrow(new Exception("error message"));
        //mock static call
        PowerMockito.mockStatic(FileHandler.class);
        Mockito.when(FileHandler.instantiateNew(anyString())).thenReturn(handler);
        
        B subject = new B();
        
        //Act
        subject.action();
        
        //Assert
        //perform assertion
    }
}

參考: 將 PowerMock 與 Mockito 一起使用

使用 mockStatic 對我來說不是一個選項,因為FileHandler用於測試的設置和拆卸,這種笨拙的方法會導致問題。

是什么從org.powermock.api.support.membermodification.MemberModifier中拯救了我的stubmethod

FileHandler mock = Mockito.mock(FileHandler.class);
Mockito.when(mock.deleteFiles(anyString()))
    .thenThrow(Exception.class);

stub(method(FileHandler.class, "instantiateNew", String.class)).toReturn(mock);

請注意,有必要通過測試 class 裝飾器准備 class FileHandler並使用 PowerMockRunner。 這是必要的,因為我們在 FileHandler 上存根 static 方法。 這是這樣做的:

@PrepareForTest({FileHandler.class})
@RunWith(PowerMockRunner.class)
public class MyTest extends MyBaseTestClass {
    @Test
    public void myTest() {
        // write test code from above here.
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM