Mockito模拟服务抛出的测试异常

问题描述

当我使用实例时,我正在尝试测试从服务抛出的异常。 就像我试图在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)上,此模拟实际上是零交互。

怎么了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)