Allow to validate this answer is correct for the given invocation.
When tests use a shared answer implementation, it may happen the answer cannot be used
with some methods. Implementing this interface indicate to Mockito it needs to verify the answer is compatible
with the stubbed interaction.
In the following example the answer is shared and work as expected...
when(mock.someMethod(anyString())).then(doSomethingTricky());
static Answer doSomethingTricky() {
return new Answer() {
Object answer(InvocationOnMock invocation) {
// tricky stuff
}
});
}
...then later there's some refactoring or some new code that want to use the answer,
however it is not compatible anymore. In this example the answer may throw an exception because
the Answer cannot work with the return type or some parameter types.
when(mock.someMethod(anyString(), anyInt())).then(doSomethingTricky()); // fail at answer execution time
when(mock.incompatibleMethod(anyVararg())).then(doSomethingTricky()); // fail at answer execution time
Instead of having an exception raised later at answer execution time, one can make this answer
validable at stub time by implementing this contract.
when(mock.incompatibleMethod(anyVararg())).then(doSomethingTricky()); // fail at answer stub time
static Answer doSomethingTricky() {
return new TrickyAnswer();
}
class Tricky Answer implements Answer, ValidableAnswer {
public Object answer(InvocationOnMock invocation) {
// tricky stuff
}
public void validateFor(InvocationOnMock invocation) {
// perform validation for this interaction
}
}