Mocking Void Methods with Mockito

By | October 15, 2020

In this post, We will learn How to mock void methods with Mockito

Usually most of the time Mockito’s org.mockito.stubbing.Stubber.when(T) method is really good enough to mock an object’s behavior but when we need to mock a void method then we can’t use when(T) method.

Mockito Mock Void Method

Mockito provides the following methods that can be used to mock void methods.

  1. org.mockito.Mockito.doAnswer(Answer): We can use  this method in Mockito when we want to stub a void method with generic Answer
  2. org.mockito.Mockito.doThrow(Throwable...): We can use this method when we want to stub a void method with an exception
  3. org.mockito.Mockito.doNothing(): We can use this method for setting void methods to do nothing. We should be beware that the void method on mocks does nothing by default. However, there are very rare situations when the doNothing() method comes handy
  4. org.mockito.Mockito.doCallRealMethod(): We  can use this method when we want to call the real implementation of a method

Mockito mock void method example

pom.xml

 

Dictionary.java

 

WordDictionary.java

 

WordDictionaryTest.java

 

The Output of the above project:

You May Also Like:

What is Mocking?
Why Need for mocking?
What are the Benefits of Mockito?
How to mock interface using Mockito example?
Mockito and JUnit Integration Using Maven Example
@Mock and @Spy Mockito Annotations With Example
@InjectMocks Annotation in Mockito with Example
Mockito – Verifying Method Calls
@Captor Annotation in Mockito with Example
Adding behavior to mocked object in Mockito
Mocking Exception Throwing using Mockito
Mockito’s mock Overloaded Methods

That’s all about Mocking Void Methods with Mockito
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.