Modify input parameter of a void function and read it afterwards

JavaJunitMockingMockito

Java Problem Overview


I have a rather complex java function that I want to test using jUnit and I am using Mockito for this purpose. This function looks something like this:

public void myFunction (Object parameter){
   ...
   doStuff();
   ...
   convert(input,output);
   ...
   parameter.setInformationFrom(output);
}

The function convert sets the attributes of output depending on input and it's a void type function, although the "output" parameter is what is being used as if it were returned by the function. This convert function is what I want to mock up as I don't need to depend on the input for the test, but I don't know how to do this, as I am not very familiar with Mockito.

I have seen basic cases as when(something).thenReturn(somethingElse) or the doAnswer method which I understand is similar to the previous one but more logic can be added to it, but I don't think these cases are appropriate for my case, as my function does not have a return statement.

Java Solutions


Solution 1 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJuanView Question on Stackoverflow
Solution 1 - JavaJeff BowmanView Answer on Stackoverflow