[英]How to verify that exception was thrown by mock method?
如何驗證下面的代碼中的模擬方法引發了異常?
它只是在檢查方法上引發異常而不會結束驗證。
// import mockito
...
@Test
public void someTest() throws Exception {
// reset and setup mock
reset(mock);
when(mock.getObj(Matchers.anyLong()))
.thenReturn(new Obj());
when(mock.save(any(Obj.class)))
.thenThrow(new RuntimeException("Error!"));
// work where mock is used (it throws no exceptions)
work();
// verify that exception on mock.save() was thrown
// ! PROBLEM HERE: exception throws right here and verify doesn't end
verify(mock, times(1)).save(any(Obj.class));
}
UPD
work()-僅向在嵌入式Kafka服務器上工作的Kafka-consumer(正在測試)發送消息。
模擬-模擬使用者邏輯中的某些對象。
在這種情況下,檢出異常是用於檢查使用者算法的某個分支的其他檢查(其他斷言不重要(已刪除):它們檢查消息是否起作用)。
我認為“工作”會引發RuntimeException嗎?
如果是這樣,您可以使用try catch來包圍work()方法,例如...
try {
work();
Assert.fail("Did not catch expected exception!");
} catch(RuntimeException ex) {
// Expected
}
verify(mock, times(1)).save(any(Obj.class));
如果沒有,您可能需要發布測試中的代碼,以使我們了解發生了什么...
編輯:仍然不是100%確定您的意思,此測試對我來說是通過...
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class Stack {
@Mock
private Mocked mock;
@Test
public void someTest() throws Exception {
reset(mock);
when(mock.getObj(Matchers.anyLong()))
.thenReturn(new Obj());
when(mock.save(any(Obj.class)))
.thenThrow(new RuntimeException("Error!"));
work();
verify(mock, times(1)).save(any(Obj.class));
}
private void work() {
Obj obj = mock.getObj(1234L);
try {
mock.save(obj);
} catch(Exception ex) {
// Bad things happened
}
}
private interface Mocked {
Obj getObj(long l);
Obj save(Obj obj);
}
public static class Obj {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.