Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito How to mock void method with output argument?

Tags:

java

mockito

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

 }
}
like image 415
guliemo Avatar asked Jan 29 '13 11:01

guliemo


1 Answers

If you can change functionVoid() to accept a mutable object as the parameter, then you should be able to achieve what you want.

For example, if you change functionVoid() as follows:

public void functionVoid(StringBuilder output_value)
{ ....
 output_value.append("test");

 ....
 }

and invoke it in your motherFunction as follows:

public String motherFunction(){
  ....
  StringBuilder test = new StringBuilder();
  myClass2.functionVoid(test);

  if (test.toString().equals("")) {

Now modifying OceanLife's answer above, you should be able to do the following:

doAnswer(new Answer<Void>() {

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

Of course, if you can change functionVoid(), you could also just make it return a String instead of void.

like image 64
mrjmh Avatar answered Oct 25 '22 03:10

mrjmh