I'm trying to achieve this behavior with Mockito:
When object of type O is applied to a method M, the mock should execute another method on the object of type O passing itself as a parameter.
Is it possible after all?
You can probably use some combination of doAnswer
and the when
combined with Mockito.any
. doAnswer
is a part of PowerMockito, which helps extend a lot of the mocking you may want to do.
NOTE, doAnswer
is used as an example for void functions. For a non-void you can use your standard Mockito.when(MOCK.call).then(RESULT)
PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
//Do whatever to Object O here.
return null;
}).when(MOCKOBJECT.methodCall(Mockito.any(O.class)));
This then does the helpful doAnswer
functionality on a mock object, and using the when
you can assign it to catch for any specific class of object (instead of having to specify an exact object it should be expecting). Using the Mockito.any(Class.class))
as part of the parameters lets Mockito know to fire off your doWhatever, when it hits a method call with ANY object of the specified type passed in.
doAnswer
method, which does precisely what you need. The solution given here (except with Mockito.doAnswer
instead of PowerMockito.doAnswer
) should work fine for you; if it doesn't, check the Mockito documentation for doAnswer
. The solution given by Tavian, using when
and thenAnswer
will work too, if the method that you want to stub is not void.
Aug 14, 2013 at 20:45
doAnswer()
is part of mockito-core-1.10.19.jar, no need to use PowerMockito