Stubbing void methods

In this recipe, we will stub a void method that doesn't return a value. The trick with void methods is that Mockito assumes that they do nothing by default, so there is no need to explicitly stub them (although you may do it).

How to do it...

If you do not want your void method to execute logic, you need to perform the following steps:

  1. Do nothing: Mockito stubs the method for you so that it does nothing.
  2. Explicitly tell Mockito that the void method does nothing; for the BDD approach, call BDDMockito.willNothing().given(mock).methodToStub(), or in the standard way, call Mockito.doNothing().when(mock).methodToStub().
  3. Regardless of the chosen approach in the given(...) or when(...) method, you have to provide the mock object (and ...

Get Mockito Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.