如何覆盖 Mockito 模拟上的默认答案?
我有以下代码:
private MyService myService;
@Before
public void setDependencies() {
myService = Mockito.mock(MyService.class, new StandardServiceAnswer());
Mockito.when(myService.mobileMethod(Mockito.any(MobileCommand.class), Mockito.any(Context.class)))
.thenAnswer(new MobileServiceAnswer());
}
我的意图是,所有对被嘲笑者的呼吁都应该以标准的方式回答。但是,对(公开的)的呼叫应以特定方式应答。myService
mobileMethod
我发现,当我到达该行以添加对调用的应答而不是附加时,Java实际上是在调用,这会导致NPE。mobileMethod
MobileServiceAnswer
myService.mobileMethod
这可能吗?似乎应该可以覆盖默认答案。如果可能的话,正确的方法是什么?
更新
这是我的:Answer
private class StandardServiceAnswer implements Answer<Result> {
public Result answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Command command = (Command) args[0];
command.setState(State.TRY);
Result result = new Result();
result.setState(State.TRY);
return result;
}
}
private class MobileServiceAnswer implements Answer<MobileResult> {
public MobileResult answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
MobileCommand command = (MobileCommand) args[0];
command.setState(State.TRY);
MobileResult result = new MobileResult();
result.setState(State.TRY);
return result;
}
}