Mockito when()

Introduction

The when() method in Mockito is used to specify the behavior of mock objects. It is part of the stubbing mechanism in Mockito, allowing you to define what should happen when a specific method on a mock object is called. This is particularly useful for isolating the code under test by providing controlled responses from dependencies. This tutorial will demonstrate how to use the when() method in Mockito to configure mock objects.

Maven Dependencies

To use Mockito with JUnit 5, add the following dependencies to your pom.xml file:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.8.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>4.8.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

Example Scenario

We will create a CalculatorService class that has a dependency on a CalculatorRepository. Our goal is to test the CalculatorService methods using the when() method in Mockito to configure the behavior of the mock CalculatorRepository.

CalculatorService and CalculatorRepository Classes

First, create the CalculatorRepository interface and the CalculatorService class.

public interface CalculatorRepository {
    int add(int a, int b);
    int subtract(int a, int b);
}

public class CalculatorService {
    private final CalculatorRepository calculatorRepository;

    public CalculatorService(CalculatorRepository calculatorRepository) {
        this.calculatorRepository = calculatorRepository;
    }

    public int performAddition(int a, int b) {
        return calculatorRepository.add(a, b);
    }

    public int performSubtraction(int a, int b) {
        return calculatorRepository.subtract(a, b);
    }
}

JUnit 5 Test Class with Mockito

Create a test class for CalculatorService using JUnit 5 and Mockito.

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class CalculatorServiceTest {

    @Mock
    private CalculatorRepository calculatorRepository;

    @InjectMocks
    private CalculatorService calculatorService;

    @Test
    public void testPerformAddition() {
        // Given
        when(calculatorRepository.add(10, 20)).thenReturn(30);

        // When
        int result = calculatorService.performAddition(10, 20);

        // Then
        assertEquals(30, result);
    }

    @Test
    public void testPerformSubtraction() {
        // Given
        when(calculatorRepository.subtract(20, 10)).thenReturn(10);

        // When
        int result = calculatorService.performSubtraction(20, 10);

        // Then
        assertEquals(10, result);
    }
}

Explanation

  1. Creating Mocks with @Mock:

    • The @Mock annotation creates a mock instance of the CalculatorRepository interface.
    • This mock instance can be used to simulate the behavior of the CalculatorRepository in a controlled way.
  2. Injecting Mocks with @InjectMocks:

    • The @InjectMocks annotation injects the mock CalculatorRepository into the CalculatorService instance to provide a controlled test environment.
    • This allows the CalculatorService methods to be tested in isolation from the actual CalculatorRepository implementation.
  3. Configuring Mock Behavior with when():

    • The when(calculatorRepository.add(10, 20)).thenReturn(30); method configures the mock CalculatorRepository to return 30 when the add method is called with the arguments 10 and 20.
    • Similarly, the when(calculatorRepository.subtract(20, 10)).thenReturn(10); method configures the mock CalculatorRepository to return 10 when the subtract method is called with the arguments 20 and 10.
  4. Testing Configured Behavior:

    • The testPerformAddition() method tests the performAddition method of the CalculatorService class. The when() method ensures that the mock CalculatorRepository returns the expected result, allowing the behavior of the performAddition method to be verified.
    • The testPerformSubtraction() method tests the performSubtraction method of the CalculatorService class. The when() method ensures that the mock CalculatorRepository returns the expected result, allowing the behavior of the performSubtraction method to be verified.

Additional Scenarios

Scenario: Configuring Multiple Behaviors

In this scenario, we will demonstrate how to configure multiple behaviors for a mock method using the when() method.

@Test
public void testMultipleBehaviors() {
    // Given
    when(calculatorRepository.add(5, 5)).thenReturn(10);
    when(calculatorRepository.add(10, 10)).thenReturn(20);

    // When
    int result1 = calculatorService.performAddition(5, 5);
    int result2 = calculatorService.performAddition(10, 10);

    // Then
    assertEquals(10, result1);
    assertEquals(20, result2);
}

Explanation

  1. Configuring Multiple Behaviors:

    • The when(calculatorRepository.add(5, 5)).thenReturn(10); method configures the mock CalculatorRepository to return 10 when the add method is called with the arguments 5 and 5.
    • The when(calculatorRepository.add(10, 10)).thenReturn(20); method configures the mock CalculatorRepository to return 20 when the add method is called with the arguments 10 and 10.
  2. Testing Configured Behaviors:

    • The testMultipleBehaviors() method tests the performAddition method of the CalculatorService class with different inputs to verify that the mock CalculatorRepository returns the expected results for each configuration.

Conclusion

The when() method in Mockito simplifies the configuration of mock objects for unit testing. By using when(), you can easily define the behavior of mock methods and test the behavior of your code in isolation. This step-by-step guide demonstrated how to effectively use the when() method in your unit tests, covering different scenarios to ensure comprehensive testing of the CalculatorService class.

Related Mockito Methods

Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers

Comments