java - JMockit 没有。 API 调用次数

标签 java jmockit

我正在测试当异常发生时 doSomething 方法是否再次在 catch block 中被调用。如何验证“doSomething”是否被调用了两次?

要测试的类:

@Service
public class ClassToBeTested implements IClassToBeTested {

@Autowired
ISomeInterface someInterface;

public String callInterfaceMethod() {
 String respObj;
 try{
     respObj = someInterface.doSomething(); //throws MyException
 } catch(MyException e){
    //do something and then try again
    respObj = someInterface.doSomething();
 } catch(Exception e){
    e.printStackTrace();
  }
 return respObj;
 }
}

测试用例:

public class ClassToBeTestedTest
{
@Tested ClassToBeTested classUnderTest;
@Injectable ISomeInterface mockSomeInterface;

@Test
public void exampleTest() {
    String resp = null;
    String mockResp = "mockResp";
    new Expectations() {{
        mockSomeInterface.doSomething(anyString, anyString); 
        result = new MyException();

        mockSomeInterface.doSomething(anyString, anyString); 
        result = mockResp;
    }};

    // call the classUnderTest
    resp = classUnderTest.callInterfaceMethod();

    assertEquals(mockResp, resp);
}
}

最佳答案

以下应该有效:

public class ClassToBeTestedTest
{
    @Tested ClassToBeTested classUnderTest;
    @Injectable ISomeInterface mockSomeInterface;

    @Test
    public void exampleTest() {
        String mockResp = "mockResp";
        new Expectations() {{
            // There is *one* expectation, not two:
            mockSomeInterface.doSomething(anyString, anyString);

            times = 2; // specify the expected number of invocations

            // specify one or more expected results:
            result = new MyException();
            result = mockResp;
        }};

        String resp = classUnderTest.callInterfaceMethod();

        assertEquals(mockResp, resp);
    }
}

关于java - JMockit 没有。 API 调用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32831281/

相关文章:

java - Java 8 流中的 arg 最大值?

java - 可以从 J2ME 查询手机的 native 收件箱吗?

java - Java 8 time api 如何选择 DST 更改周期的偏移量

jmockit - 记录期望的位置无效

java - 解决java包依赖关系

java - 无法将对象添加到实例化为 ArrayList<Object> 的 List<?>

Java:如何对在方法范围内创建和操作文件的方法进行单元测试?

java - 如何使用jmockit模拟私有(private)类?

java - MyClass 在两次测试之间保持模拟状态

java - 使用 @Mocked 多次模拟同一类时的 JMockit 行为