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!
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.