Sometimes you need to stub a class only for a method and you may need to add some behavior to that stubbed mehod like get a value from a map and return it.
Instead of just returning an object for the stubbed method like:
when(mock.aMethod(anyString())).thenReturn("a static result");
you can return a dynamic result by using stubbing with callbacks feature of Mockito.
when(mock.aMethod(anyString())).thenAnswer(new Answer<MyObject>() {
MyObject answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
//you can do some stuff using args
return ...;
}
});
In answer method you can access the mocked object itself :
Object mock = invocation.getMock();
By the way, this brings a bit complexity to your test. If you don’t really need it, do not use it.
Don’t forget simplicity.
