我有以下服務和測驗方法,我正在嘗試代碼執行catch (ApplicationException e) { }塊。
public abstract class ApplicationException extends RuntimeException {
// ....
}
public void create(Request request) {
try {
// ...
} catch (ApplicationException e) {
// I want the code hits this block and check the values in here
}
}
下面是測驗方法:
@InjectMocks
private ProductServiceImpl productService;
@Test
public void test() {
// variable defnitions and stubbings (code omitted)
willAnswer( invocation -> { throw new RuntimeException("abc msg"); })
.given(productService).create(request);
// or
// doThrow(new RuntimeException()).when(productService).create(request);
// service method call
productService.create(Request request);
}
當我除錯代碼時,我doThrow在線收到錯誤:
org.mockito.exceptions.misusing.NotAMockException:傳遞給 when() 的引數不是模擬!
那么,我該如何解決這個問題呢?
uj5u.com熱心網友回復:
正如@Jesper 在評論中提到的那樣,您沒有正確使用 Mockito。
對于您的測驗用例,您需要測驗您的ProductService.create方法是否可以處理給定場景中的錯誤。讓我們假設您的代碼看起來像這樣。
class ProductService {
private SomeOtherService someOtherService;
public void create(Request request) {
try {
someOtherService.execute();
} catch (ApplicationException e) {
// I want the code hits this block and check the values in here
enter code here
throw new MyException(e); // Here you can do something else
}
}
所以someOtherService.execute可以拋出ApplicationException。我們需要測驗我們是否ProductService.create會捕獲該例外并進行一些處理。在示例中,我們將只拋出不同型別的例外。
@Mock
private SomeOtherService mockOtherService;
@InjectMocks
private ProductServiceImpl productService;
@Test
public void test() {
doThrow(new ApplicationException()).when(someOtherService).execute();
given(productService.create(request)).willThrow(new MyException());
}
因此,與您的示例的主要區別在于,我們告訴 SomeOtherService 模擬它在呼叫 execute 方法時應該做什么。這是允許的,Mockito 知道如何使用模擬。
在您的示例中,您試圖傳遞一個真實的物件而不是一個模擬物件。@InjectMock注釋是這個的簡寫
this.productService = new ProductService(mockSomeOtherService);
所以它創建了一個新物件,它的依賴被模擬了。有關此的更多資訊,您可以在此處找到https://stackoverflow.com/a/16467893/2381415。
我沒有運行此代碼或測驗它,所以不要 C/P 它。
希望它可以幫助您了解您的方法出了什么問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/461179.html
