Mockito times() Method Example

1. Introduction

While unit testing in Java with Mockito, sometimes it's crucial to check not only if a specific method of a mock object was called but also how many times it was invoked. Mockito's times() method provides this ability, allowing testers to ensure that certain interactions with mock objects occur the exact number of times as expected.

2. Example Steps

1. Create an interface with a method we wish to test.

2. Create a concrete class that implements this interface.

3. Set up a test class for the interface.

4. Mock the interface with Mockito.

5. Invoke the method on the mocked object multiple times.

6. Use Mockito's times() combined with verify() to confirm the number of invocations of the method.

7. Execute the test.

3. Mockito times() Method Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

// Step 1: Create an interface
interface Messenger {
    void sendMessage(String message);
}

// Step 2: Implement the interface
class TextMessenger implements Messenger {
    @Override
    public void sendMessage(String message) {
        System.out.println("Message sent: " + message);
    }
}

public class MessengerTest {

    @Test
    public void testSendMessageInvocation() {
        // Step 4: Mock the Messenger interface
        Messenger mockedMessenger = mock(Messenger.class);

        // Step 5: Use the mocked object multiple times
        mockedMessenger.sendMessage("Hello");
        mockedMessenger.sendMessage("Hi");
        mockedMessenger.sendMessage("Hey");

        // Step 6: Use Mockito's times() method to check the number of invocations
        verify(mockedMessenger, times(3)).sendMessage(anyString());
    }
}

Output:

The test will run successfully, confirming that the sendMessage method of the mocked object was called exactly three times.

4. Step By Step Explanation

1. We begin with a simple Messenger interface that has a method to send a message.

2. The TextMessenger class provides a basic implementation by printing the sent message to the console.

3. In the MessengerTest class, the real action takes place. The Messenger interface gets mocked.

4. This mocked messenger is used to send three different messages.

5. After these invocations, we use the combination of verify() and times() to assert that the sendMessage method was invoked thrice, regardless of the actual message content.

6. This test showcases the utility of the times() method in validating the expected frequency of interactions with mock objects, ensuring that our system under test adheres to expected behaviors and interaction patterns.


Comments