当我使用实例时,我正在尝试测试从服务抛出的异常。 就像我试图在Trans.class中使用Imock并使用IMock方法。 下面是代码
public class MockImpl implements IMock{
public String external(String str) throws Exception {
if(str.equals("throw")){
throw new Exception("Thrown exception.");
}
return str;
}
}
public class Trans {
private IMock mc;
public static int failed;
public String performTrans(String str) throws Exception {
return call(str);
}
private String call(String str) throws Exception {
mc = new MockImpl();
try {
return mc.external(str);
}
catch(Exception e){
failed++;
throw e;
}
}
}
在测试课中,我正在尝试这样做
public class TestMock {
@Test
public void testMock() throws Exception {
Trans trans = mock(Trans.class);
IMock iMock = mock(IMock.class);
doThrow(new Exception()).when(iMock).external(any(String.class));
for(int i =0;i<10 ;i++){
trans.performTrans("any");
}
System.out.println(Trans.failed);
assertEquals(9, Trans.failed);
}
}
由于我是新手,所以不确定我的理解是否正确,我要实现的目标是 当我做#Trans.performTrans(String); 然后doThrow(new Exception())。when(iMock).external(any(String.class));应该会发生。 我如何告诉Mockito或任何测试框架,应该从Imock服务方法模拟应该抛出的异常,即使它是间接调用的也是如此。
更新
尝试通过这种方式进行测试之后 @RunWith(MockitoJUnitRunner.class) 公共类TestMock {
@Test
public void testMock() throws Exception {
Trans trans = new Trans();
IMock iMock = mock(IMock.class);
trans.setInter(iMock);
//doThrow(new Exception()).when(iMock).external(any(String.class));
trans.performTrans("abc");
verify(iMock).external(new String("a"));
System.out.println(Trans.failed);
assertEquals(9, Trans.failed);
}
}
我收到此错误。
想要但不被调用:iMock.external(“ a”); -> com.app.TestMock.testMock(TestMock.java:32)上,此模拟实际上是零交互。
怎么了?