How to mock a void return method affecting an object

To add to Kevin Welker's answer, if your MyClass is a custom class, then define a equals/hashcode method in it, so that Mockito can use it to match to the method call exactly.

In my case, "MyClass" was in a third-party API, so I had to use the method "any" as below -

 doAnswer(new Answer() {
    Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();
        ((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
        return null; // void method, so return null
    }
}).when(mock).someMethod(any(MyClass.class));

The answer is yes, you can, and there are basically two levels of doing this, based on the need of your test.

If you merely want to test the interaction with the mocked object, you can simply use the verify() method, to verify that the void method was called.

If your test genuinely needs the mocked object to modify parameters passed to it, you will need to implement an Answer:

EDITED to show proper form of using Answer with void method

doAnswer(new Answer() {
    @Override
    Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();
        ((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
        return null; // void method, so return null
    }
}).when(mock).someMethod();

In Java 8+, the above is simplified with a lambda:

doAnswer(invocation-> {
    Object[] args = invocation.getArguments();
    ((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
    return null;
}).when(mock).someMethod();

Tags:

Java

Mockito