Mockito Stubbing Void Methods

Introduction

In this chapter, we will learn about stubbing void methods with Mockito. Void methods do not return a value, but you can still control their behavior using stubbing. You might want to stub void methods to do nothing, throw an exception, or perform some custom action.

What is Stubbing?

Stubbing is the process of specifying what mock objects should do when their methods are called. By defining the behavior of mock objects, you can control their interactions and ensure that your tests are reliable and predictable. Stubbing allows you to return specific values, throw exceptions, or execute custom logic when a method is called.

Stubbing Void Methods

Void methods do not return a value, but you can still control their behavior. This can be useful in situations where you want to ensure that the method is called without performing its actual logic or to simulate exceptional conditions.

Example: EmailService Class and EmailServiceTest Class

Class Under Test: EmailService

public class EmailService {
    public void sendEmail(String recipient, String message) {
        // Logic to send email
        System.out.println("Sending email to " + recipient + ": " + message);
    }
}

Test Class: EmailServiceTest

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

public class EmailServiceTest {

    @Test
    void testVoidMethod() {
        // Create a mock object of EmailService
        EmailService emailService = mock(EmailService.class);

        // Stub the void method to do nothing
        doNothing().when(emailService).sendEmail(anyString(), anyString());

        // Call the void method
        emailService.sendEmail("test@example.com", "Hello");

        // Verify that the void method was called
        verify(emailService).sendEmail("test@example.com", "Hello");
    }

    @Test
    void testVoidMethod_ThrowException() {
        // Create a mock object of EmailService
        EmailService emailService = mock(EmailService.class);

        // Stub the void method to throw an exception
        doThrow(new RuntimeException("Exception occurred")).when(emailService).sendEmail(anyString(), anyString());

        // Call the void method and handle the exception
        RuntimeException exception = assertThrows(RuntimeException.class, () -> {
            emailService.sendEmail("test@example.com", "Hello");
        });

        assertEquals("Exception occurred", exception.getMessage());
    }
}

Explanation

  1. Creating a Mock:
    EmailService emailService = mock(EmailService.class);
    

    This line creates a mock object of the EmailService class.

  2. Stubbing to Do Nothing:
    doNothing().when(emailService).sendEmail(anyString(), anyString());
    

    This line stubs the sendEmail method to do nothing when called with any string arguments.

  3. Calling the Void Method:
    emailService.sendEmail("test@example.com", "Hello");
    

    This line calls the sendEmail method on the mock object.

  4. Verifying Interactions:
    verify(emailService).sendEmail("test@example.com", "Hello");
    

    This line verifies that the sendEmail method was called with the specified arguments.

  5. Stubbing to Throw an Exception:
    doThrow(new RuntimeException("Exception occurred")).when(emailService).sendEmail(anyString(), anyString());
    

    This line stubs the sendEmail method to throw a RuntimeException when called with any string arguments.

  6. Handling the Exception:
    RuntimeException exception = assertThrows(RuntimeException.class, () -> {
        emailService.sendEmail("test@example.com", "Hello");
    });
    

    This line calls the sendEmail method on the mock object and checks that the expected exception is thrown.

Running Tests using IntelliJ IDEA

Mockito Stubbing Void Methods

Conclusion

Stubbing void methods with Mockito allows you to control their behavior in your tests. By using methods like doNothing(), doThrow(), and doAnswer(), you can simulate different scenarios and ensure that your code interacts with its dependencies as expected. This makes your tests more flexible and reliable, helping you catch potential issues early in the development process.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top