Mocking Void Methods with Mockito Example

1. Introduction

Mocking methods that return void in Mockito can be a bit tricky since we can't use the usual when(...).thenReturn(...) approach. However, Mockito provides ways to handle this scenario, especially for stubbing and verifying behaviors of void methods.

2. Example Steps

1. Create a simple service with a void method.

2. Mock this service in a test class.

3. Use Mockito's doNothing(), doThrow(), or doAnswer() to stub the behavior of the void method.

4. Call the void method on the mock.

5. Verify the behavior of the void method using Mockito's verify() method.

3. Mocking Void Methods with Mockito Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

public class LoggerService {
    public void logMessage(String message) {
        // Logic to log the message
    }
}

public class LoggerServiceTest {

    @Test
    public void testLogMessageMocking() {
        // Mock the LoggerService
        LoggerService mockedLoggerService = mock(LoggerService.class);

        // Stubbing the logMessage method to throw an exception when called
        doThrow(new RuntimeException("Mocked Exception")).when(mockedLoggerService).logMessage(anyString());

        try {
            // Calling the method on the mock
            mockedLoggerService.logMessage("Test message");
        } catch (RuntimeException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }

        // Verifying the method's behavior
        verify(mockedLoggerService).logMessage("Test message");
    }
}

Output:

Caught exception: Mocked Exception

4. Step By Step Explanation

1. We created a simple LoggerService class with a void method named logMessage.

2. In the LoggerServiceTest class, we mocked the LoggerService.

3. To stub the behavior of the logMessage void method, we used the doThrow() method. We specified that when the logMessage method of the mock object is called with any String, it should throw a RuntimeException with the message "Mocked Exception".

4. We then invoked the logMessage method on the mock object, which threw the exception as expected. We caught the exception and printed its message.

5. Finally, using the verify() method, we ensured that the logMessage method was indeed called with the String "Test message".

6. The output "Caught exception: Mocked Exception" confirms that the stubbing of the void method was successful.


Comments