Mockito is one of the best testing frameworks used to mock objects and verify methods behavior. In this article, we are going to present a way to stub a method that returns void instead of an Object. Stubbing void methods require a different approach.
2. Stubbing void methods
First, let's check what happens when we try to use the
when(...).then(...) notation to configure a method that returns void.
In the following example test, we have a simple interface with the
doSomething() void method that we want to mock. We want to throw an exception every time we call that method.
when(simpleInterface.doSomething()).thenThrow(new RuntimeException("Something is not right")); will give us a compilation error:
The compiler doesn't like void methods inside brackets thats why we need to use a different solution here - we should use doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() family of methods.
doThrow().when() notation instead of
This code was compiled successfully, without any errors. Test also passed without any issues.
According to the Mockito docs the
do...().when(...) family of methods we used to:
- stub void methods,
- stub methods on spy objects,
- stub the same method more than once, to change the behavior of a mock in the middle of a test.
We can use these methods also as an alternative with
when() for all stubbing calls.
In this article, we presented how to stub a method that returns void in Mockito tests. This kind of methods should be treated differently. Instead of
when().then() notation we must use
As usual, the code used in this article is available under our GitHub repository.