Java
Mockito
Unit Testing
Verify Method Calls
Test Automation

Java verify void method calls n times with Mockito

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction to Mockito

Mockito is a popular open-source testing framework for Java that allows developers to create mock objects for unit testing. Its key feature is the ability to verify whether specific methods were invoked on mock objects during the test execution. This feature helps ensure code behaves as expected by allowing fine-grained control over the method interactions on these objects.

Verifying Void Method Calls with Mockito

In certain scenarios, developers may need to verify that a void method is called a specific number of times. Mockito makes this possible even though void methods do not return values. The framework provides a fluent API to verify these invocations, which is especially useful for methods that alter the state or interact with external systems.

Key Methods for Verification

Mockito offers several methods for verifying interactions, the most notable being:

  • verify()
  • times()
  • never()
  • atLeast(int)
  • atMost(int)

Using verify()

The verify() method checks whether a specific method has been called on a mocked object. It supports custom verification modes such as times() to specify the exact number of invocations expected.

Syntax:

java
verify(mockObject, times(N)).methodName(params);

Here, mockObject is the mock reference, times(N) specifies the expected number of calls, and methodName(params) refers to the method under verification.

Example: Verifying a Method Call N Times

Consider a scenario where you have a Notifier interface with a void method sendNotification():

java
public interface Notifier {
    void sendNotification(String message);
}

Suppose you want to ensure this method is invoked exactly 3 times during a test. Here’s how you would write the test case using Mockito:

java
1import static org.mockito.Mockito.*;
2
3public class NotifierTest {
4    public static void main(String[] args) {
5        
6        // Create mock object
7        Notifier notifier = mock(Notifier.class);
8
9        // Simulate method calls
10        notifier.sendNotification("Hello");
11        notifier.sendNotification("Hello");
12        notifier.sendNotification("Hello");
13
14        // Verify that sendNotification() is called 3 times
15        verify(notifier, times(3)).sendNotification("Hello");
16    }
17}

Beyond times(int) — Other Verification Modes

  • never(): Verifies the method was never called.
java
  verify(mockObject, never()).methodName(params);
  • atLeast(int): Checks if a method was called at least a specific number of times.
java
  verify(mockObject, atLeast(2)).methodName(params);
  • atMost(int): Ensures a method is called at most a certain number of times.
java
  verify(mockObject, atMost(2)).methodName(params);

Practical Applications

Event-driven Systems

In an event-driven architecture, event handling methods might need verification to ensure events are consumed the expected number of times. Mockito’s verification can confirm the event processing logic’s integrity.

State Management

For applications managing state, verifying method calls helps ensure state transitions occur correctly. Methods responsible for changing the state should be verified to detect unwanted behavior.

Service Layer Testing

In a layered architecture, service methods are focal points for verification. They often invoke several data access methods, and checking their invocation count can validate business logic correctness.

Summary Table

Here's a quick summary of Mockito's core verification features:

FeatureDescriptionExample Usage
verify()Verifies if a method was calledverify(mock).methodName();
times(int)Verifies exact invocation countverify(mock, times(3)).methodName();
never()Ensures the method was never calledverify(mock, never()).methodName();
atLeast(int)Ensures method is called at least N timesverify(mock, atLeast(1)).methodName();
atMost(int)Ensures method is called at most N timesverify(mock, atMost(2)).methodName();

Conclusion

Mockito's ability to verify method calls precisely allows developers to test for specific behaviors in their code. This feature is critical for scenarios where void methods drive functionality, such as notifications, event handling, or database updates. By leveraging Mockito’s verification capabilities, developers can ensure their code adheres to the required specifications, providing confidence in both the correctness and stability of Java applications.


Course illustration
Course illustration

All Rights Reserved.