Introduction
In this post, we will look at how to mock void methods with Mockito. Methods that return void can't be used with when. This means we have to work with the following methods to mock a void method:
doThrow(Throwable...)
doThrow(Class)
doAnswer(Answer)
doNothing()
doCallRealMethod()
This is the class we will be using for the examples. It's a small class with only one void method that prints “Hello, " followed by the input to the console.
|
|
Throwing an exception with a mocked void method
To make a void method throw an exception, we use doThrow()
. The exception we pass to the doThrow()
is thrown when the mocked
method is called.
|
|
You can only use unchecked exceptions or exceptions that are declared in the method signature. The doThrow()
call below
wouldn't work because IOException
is a checked exception and not declared as part of the doAction()
method signature.
|
|
Verifying that a void method is called
With Mockito, we use verify()
to check if a method has been called. The example below shows two ways of implementing this.
times(1)
is the default value, so you can omit it to have more readable code.
|
|
Capturing void method arguments
We can also capture the arguments that we pass to a method. To do that we can create an ArgumentCaptor
or use lambda matchers.
Line 4 till 6 shows how to create and use the ArgumentCaptor
. Lines 9 uses a lambda matcher. At line 11, we also use a lambda matcher,
but with a method reference to keep it more readable.
|
|
Stub a void method to run other code
We can also stub a method to let it perform other behavior. We use Mockito's doAnswer()
to change the behavior.
The example below changed the message that gets printed to the console. The method will now print good morning instead
of hello.
|
|
Calling the real method
By default, stubbed will do nothing when you call them. To call the actual method, you can use doCallRealMethod()
. Doing this
will let you call the actual method of the class you mock.
|
|
Conclusion
In this post, we looked at the different ways of mocking void methods when you write tests using Mockito. You learned how to mock void methods with Mockito using different methods.