20

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!

John B
  • 32,493
  • 6
  • 77
  • 98
Mat
  • 515
  • 3
  • 8
  • 13

1 Answers1

18

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

John B
  • 32,493
  • 6
  • 77
  • 98
  • Yes this works! Can't believe how simple that was :) – Mat Jul 29 '14 at 15:06
  • 13
    Note that `when(spy.myMethod()).thenReturn(null)` does not work (in the general case, it might in a specific case) for a spy because the method's actual implementation will be executed at this point. The general rule is that spies must always be stubbed with the `doXyz().when(spy).method()` syntax to prevent accidental execution of the real code. – Rogério Jul 29 '14 at 20:15