Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito / PowerMocktio doNothing for none void method

Tags:

I need a method which returns something to do nothing when invoked during testing, the class instance which owns the method is implemented as a spy.

I am aware the doNothing() method only works with void methods. Is there a way to get the same behaviour with a method that returns something?

Thank you!

like image 919
Mat Avatar asked Jul 29 '14 14:07

Mat


1 Answers

Use when(spy.myMethod()).thenReturn(null). This will prevent the spy from invoking the wrapped instance. You have to tell Mockito what to return for a method that returns something. The default behavior for a mock is to return null. The default behavior for a spy is to call the wrapped object. When you stub a method in a spy it prevents the call to the wrapped object and executes the specified behavior.

Per documents of Spy, you could also do doReturn(null).when(spy).myMethod();

like image 193
John B Avatar answered Sep 16 '22 21:09

John B