Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: How to get the arguments passed to a method when the return type of the method is void

Tags:

java

mockito

I've read this post, but my problem is that my myFunction returns void instead of an Object. So I get errors at

when(mock.myFunction(anyString()))

saying

when (java.lang.Void) in Mockito cannot be applied 
to   (void)

How can I deal with this issue?

like image 464
goldfrapp04 Avatar asked May 23 '14 20:05

goldfrapp04


People also ask

How do you mock method which returns void?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

What assert in void method?

Whenever we write unit test cases for any method we expect a return value from the method and generally use assert for checking if the functions return the value that we expect it to return, but in the case of void methods, they do not return any value.

What is doNothing in Mockito?

However, doNothing() is Mockito's default behavior for void methods. This version of whenAddCalledVerified() accomplishes the same thing as the one above: @Test public void whenAddCalledVerified() { MyList myList = mock(MyList.class); myList.add(0, ""); verify(myList, times(1)).add(0, ""); }


2 Answers

I have the same answer in a comment on the question, but just to make it easier for future readers to see, here it is.

doNothing().when(mock).myFunction(anyString());

in order to be able to handle the void return type.

like image 116
geoand Avatar answered Oct 11 '22 03:10

geoand


The answer to this can be found in my answer to that other post that you linked to.

doAnswer(returnsFirstArg()).when(mock).myFunction(anyString());

where the returnsFirstArg() method is static in the AdditionalAnswers class.

like image 37
Dawood ibn Kareem Avatar answered Oct 11 '22 02:10

Dawood ibn Kareem