I have the following code:
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());
}
My intention is that all calls to the mocked myService should answer in a standard manner. However calls to mobileMethod (which is public) should be answered in a specific way.
What I'm finding is that, when I get to the line to add an answer to calls to mobileMethod, rather than attaching the MobileServiceAnswer, Java is actually invoking myService.mobileMethod, which results in an NPE.
Is this possible? It would seem like it should be possible to override a default answer. If it is possible, what is the correct way to do it?
Update
Here are my Answers:
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;
}
}