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?
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.
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.
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, ""); }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With