Mockito How to mock void method with output argument?

java, mockito

Solution

If you want to mock the return result of `motherFunction` then you need not worry about the internal implementation of the method (which ends up calling `functionVoid`). What you do need to do is provide Mockito with an instruction as to what to do when the method, `motherFunction` is invoked, this can be achieved via the when clause with syntax;

    when(mockedObject.motherFunction()).thenReturn("Any old string");

If that misses the point of what you are attempting to achieve then look at how to mock void methods in the documentation and determine whether the use of `doAnswer` is applicable here, something like;

doAnswer(new Answer<Void>() {

  @Override
  public Void answer(InvocationOnMock invocation) throws Throwable {
    String output_value = invocation.getArguments()[0];
    output_value = "Not blank";
    return null;
  }
}).when(myClass2).functionVoid(anyString());

Problem

I have a void method "functionVoid" that informs a parameter. ``` public class MyMotherClass { @Inject MyClass2 myClass2 public String motherFunction(){ .... String test = ""; myClass2.functionVoid(test); if (test.equals("")) { IllegalArgumentException ile = new IllegalArgumentException( "Argument is not valid"); logger.throwing(ile); throw ile; } .... } } public class MyClass2 { public void functionVoid(String output_value) { .... output_value = "test"; .... } } ``` How do I mock this method in the JUnit method my method "motherFunction"? In my example, the "test" variable is still empty. ``` @RunWith(MockitoJUnitRunner.class) public class MyMotherClassTest { @Mock private MyClass2 myClass2 ; @InjectMock private final MyMotherClass myMotherClass = new MyMotherClass (); @Test public void test(){ myMotherClass.motherFunction(); } } ```

Original source

Related problems