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?
To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().
Mockito Verify methods are used to check that certain behavior happened. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With