Mockito @Mock Annotation

Introduction

In this chapter, we will learn about the @Mock annotation in Mockito. This annotation is used to create mock objects, which can then be used to stub methods and verify interactions in unit tests.

Key Points about the @Mock Annotation

  • Creates Mock Objects: The @Mock annotation creates mock objects that simulate the behavior of real objects.
  • Simplifies Setup: It simplifies the setup of tests by automatically generating mocks.
  • Used with @InjectMocks: Often used with the @InjectMocks annotation to inject the created mocks into the class under test.
  • Initialization: Requires initialization using MockitoAnnotations.openMocks(this).

Setting Up Mockito for @Mock Annotation

Ensure that you have the necessary dependencies in your pom.xml if you are using Maven:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>5.2.0</version>
        <scope>test</scope>
    </dependency>
    <!-- JUnit 5 dependency -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Example: Using @Mock Annotation

Description

In this example, we will create a CalculatorService class that depends on a MathService class. The CalculatorService class will use the MathService class to perform addition and subtraction operations. We will create unit tests for the CalculatorService class using Mockito’s @Mock annotation to mock the MathService class.

Class Under Test: CalculatorService

public class CalculatorService {
    private final MathService mathService;

    public CalculatorService(MathService mathService) {
        this.mathService = mathService;
    }

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

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

Supporting Class: MathService

public class MathService {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

Test Class: CalculatorServiceTest

import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorServiceTest {

    @Mock
    private MathService mathService;

    private CalculatorService calculatorService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        calculatorService = new CalculatorService(mathService);
    }

    @Test
    void testAdd_Success() {
        // Arrange
        when(mathService.add(10, 20)).thenReturn(30);

        // Act
        int result = calculatorService.add(10, 20);

        // Assert
        assertEquals(30, result);
        verify(mathService).add(10, 20);
    }

    @Test
    void testSubtract_Success() {
        // Arrange
        when(mathService.subtract(20, 10)).thenReturn(10);

        // Act
        int result = calculatorService.subtract(20, 10);

        // Assert
        assertEquals(10, result);
        verify(mathService).subtract(20, 10);
    }
}

Explanation

  1. Mock Annotation:
    @Mock
    private MathService mathService;
    

    The @Mock annotation creates a mock object for the MathService class.

  2. Initializing Mocks:
    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        calculatorService = new CalculatorService(mathService);
    }
    

    The MockitoAnnotations.openMocks(this) method initializes the mock objects. This is typically done in a @BeforeEach method to ensure mocks are reset before each test.

  3. Test Method:
    @Test
    void testAdd_Success() {
        // Arrange
        when(mathService.add(10, 20)).thenReturn(30);
    
        // Act
        int result = calculatorService.add(10, 20);
    
        // Assert
        assertEquals(30, result);
        verify(mathService).add(10, 20);
    }
    

    This test method sets up the mock behavior (Arrange), calls the method under test (Act), and checks the expected results (Assert). It verifies that the mock’s method was called with the expected arguments.

Output

Mockito @Mock Annotation

Conclusion

The @Mock annotation in Mockito is used for creating mock objects. It simplifies the setup of tests by automatically generating mocks, which can be used to stub methods and verify interactions. In this section, we demonstrated how to use the @Mock annotation with a simple CalculatorService example. This approach helps make your tests cleaner and more maintainable.

Leave a Comment

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

Scroll to Top