Mockito verify() Method Example

1. Introduction

Mockito provides a suite of methods and utilities to make unit testing in Java efficient and expressive. One of the powerful methods at a tester's disposal is the verify() method. This method ensures that a certain interaction with the mock object has taken place. It allows testers to confirm not only the invocation of methods on mocked objects but also the number of times they were called, allowing precise control and verification of mock interactions.

2. Example Steps

1. Define an interface with a simple method.

2. Implement this interface in a concrete class.

3. Create a test class for the interface.

4. Mock the interface using Mockito.

5. Use the mocked object in a manner where the method would be invoked.

6. Use Mockito's verify() method to check if the method was indeed invoked on the mock object.

7. Run the test.

3. Mockito verify() 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: Define an interface
interface Logger {
    void logMessage(String message);
}

// Step 2: Implement the interface in a concrete class
class SimpleLogger implements Logger {
    @Override
    public void logMessage(String message) {
        System.out.println(message);
    }
}

public class LoggerTest {

    @Test
    public void testLogMessageInvocation() {
        // Step 4: Mock the Logger interface
        Logger mockedLogger = mock(Logger.class);

        // Step 5: Use the mocked object
        mockedLogger.logMessage("Hello, Mockito!");

        // Step 6: Use Mockito's verify() method to check method invocation
        verify(mockedLogger, times(1)).logMessage("Hello, Mockito!");
    }
}

Output:

The test will run successfully, indicating that the logMessage method of the mocked object was indeed invoked once with the specified argument.

4. Step By Step Explanation

1. The Logger interface is created, having a method named logMessage which logs a message.

2. A simple implementation of the interface, SimpleLogger, is provided, which prints the message to the console.

3. In the LoggerTest class, the real testing action unfolds. The Logger interface is mocked.

4. The mocked logger is then used to log a message.

5. After the invocation, Mockito’s verify() method is used to check that the logMessage method was called exactly once with the given argument.

6. This test emphasizes the ability of the verify() method to confirm the number and type of interactions with a mock object. This helps to ensure the expected behavior and interaction patterns of the system under test.


Comments