Modify input parameter of a void function and read it afterwards
Solution 1:
If you want the mocked method to call a method on (or otherwise alter) a parameter, you'll need to write an Answer as in this question ("How to mock a void return method affecting an object").
From Kevin Welker's answer there:
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();
Note that newer best-practices would have a type parameter for Answer, as in Answer<Void>
, and that Java 8's lambdas can compress the syntax further. For example:
doAnswer(invocation -> {
Object[] args = invocation.getArguments();
((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
return null; // void method in a block-style lambda, so return null
}).when(mock).someMethod();