[英]Mocking a void method in the same class that is under test with mockito and junit5?
[英]Test error handling method weirdness with Junit5 and mockito
我正在對執行一些異常處理的方法進行單元測試。 這是我要測試的簡化類:
class Foo{
private BarService bar;
public int MethodToTest(){
try{
bar.methodThatThrows();
return 1;
}catch(Exception e){
return 0;
}
}
}
這是單元測試課程。
class FooTest{
private IBarService barService = mock(BarService.class);
@Test
TestMethodToTest(){
when(barService.methodThatThrows()).thenThrow(new Exception("message");
Foo foo = new foo();
ReflectionTestUtils.setField(foo, "barService", barService);
assertEquals(foo.MethodToTest(), 0);
}
}
以某種方式,當我運行它時,它會失敗,因為拋出了一個錯誤(如預期的那樣),該錯誤與我放入模擬服務中的消息具有完全相同的消息。 當我在調試模式下運行時,catch塊甚至沒有運行。 這怎么可能?
您很有可能在測試中拋出了未針對methodThatThrows
聲明的檢查異常
您在測試中聲明的消息確實已打印到控制台,但該消息更具參考價值:
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception: message
例如(在BarService中聲明了IOException,但在測試代碼中拋出了更一般的檢查異常):
public class BarService {
public int methodThatThrows() throws IOException {
return 1;
}
}
您沒有在示例代碼中正確設置BarService
。 你在做:
ReflectionTestUtils.setField(foo, "barService", barService);
但是在Foo
類中, BarService
變量稱為“ bar”,而不是“ barService”,因此您需要執行以下操作:
ReflectionTestUtils.setField(foo, "bar", barService);
盡管執行此操作的“正確”方法是使用Spring將BarService
自動BarService
到Foo
,這使您不必首先使用ReflectionTestUtils
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.