Mockito:定义模拟行为

时间:2014-09-17 13:16:24

标签: unit-testing mocking mockito

我正在尝试测试一个类,这取决于外部服务。此外部服务修改传递给它的对象:

public void methodF(Op op) {

    ...

    // op.operationId == 0

    externalService.registerOp(op);

    // op.operationId == 123456L

    if (op.getOperationId() == 0) {
        throw new CustomException();
    }

}

如果我模拟外部服务,它不会修改操作,正在测试的整个方法会失败,但会有例外。

如何定义假冒修改操作的模拟行为?

1 个答案:

答案 0 :(得分:10)

您可以write an Answer为模拟方法提供任意实现。

doAnswer(new Answer<Void>()) {
  @Override public Void answer(InvocationOnMock invocation) throws Throwable {
    Op argument = (Op) invocation.getArguments()[0];

    // Your code here
    argument.operationId = 123456;

    return null;
  }
}).when(externalService).registerOp(any(Op.class));

对于非空方法,您也可以使用thenAnswer代替doAnswer

如果您发现自己一遍又一遍地编写相同的答案,或者在同一个类上模拟许多操作,请考虑编写一个替代实现(例如FakeExternalService或UnitTestExternalService)直接存根此操作,这可能更具可读性和更多类型-safe。