How to mock void methods with Mockito
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Mockito is a popular mocking framework for Java, typically used for unit testing. It allows developers to isolate the unit of work by creating mock objects and manipulating how these objects behave when specific methods are invoked. When it comes to mocking void methods, Mockito provides several useful techniques to handle these cases effectively. This article explores the hows and whys of mocking void methods using Mockito, with a focus on real-world applications and usefulness in unit testing.
Understanding Void Methods in Testing
Void methods do not return a value. They often perform operations like setting a value, sending data to a database or another service, or simply logging information. Testing these methods involves ensuring that they were called as expected, or that they alter the system's state in desired ways.
Techniques to Mock Void Methods
1. Using doNothing()
The default behavior of Mockito when mocking void methods is to do nothing. However, explicitly using doNothing() is useful when you need to override this behavior in specific cases, particularly when using spy objects.
Example:
2. Using doThrow()
doThrow() is used when you want a mock to throw an exception when a void method is called. This is useful in testing exception handling within your code.
Example:
3. Using doAnswer()
Mockito’s doAnswer() is a flexible mechanism which can be used with void methods where you need to perform some operations when the method is called.
Example:
Summary Table
| Method | Use Case | Example Calling |
doNothing() | When you want a void method to do nothing. | doNothing().when(mock).methodName(); |
doThrow() | When you want a void method to throw an exception | doThrow(new Exception()).when(mock).methodName(); |
doAnswer() | When operations are needed within a void method | doAnswer(invocation -> {... return null; }).when(mock).methodName(); |
Additional Considerations
- Verification: Beyond simply mocking void methods, you might also want to verify that they were called with the correct parameters or a specific number of times. This can be crucial for methods that impact the state of an application.
- Spy vs. Mock: Consider using spies when you want to mock certain behavior while still calling the real methods of an object. Spies are particularly useful when you want most of the object's original behavior to remain intact.
In conclusion, Mockito offers various options for effectively mocking void methods, aiding in thorough testing of side-effects and interactions within your codebase. Remember, the goal of using these techniques is to create clear, robust, and effective tests that help maintain and improve the quality of your software.

