Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Mockito do something every time the method on the mock is called?

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?

like image 992
kboom Avatar asked Aug 14 '13 17:08

kboom


People also ask

How do you know if a mock method is called?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

Does mock object call real method?

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().

Does Mockito verify call the method?

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.


1 Answers

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.

like image 151
Walls Avatar answered Oct 15 '22 19:10

Walls