0
0
JUnittesting~10 mins

@InjectMocks annotation in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the @InjectMocks annotation to create an instance of the class under test and automatically inject its mocked dependencies. It verifies that the method returns the expected result using the injected mocks.

Test Code - JUnit 5 with Mockito
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class CalculatorServiceTest {

    @Mock
    private Calculator calculator;

    @InjectMocks
    private CalculatorService calculatorService;

    @Test
    public void testAdd() {
        when(calculator.add(2, 3)).thenReturn(5);
        int result = calculatorService.add(2, 3);
        assertEquals(5, result);
    }
}

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

class CalculatorService {
    private Calculator calculator;

    public int add(int a, int b) {
        return calculator.add(a, b);
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test framework initializes and processes @ExtendWith(MockitoExtension.class) to enable Mockito supportMockitoExtension is active, ready to process mocks and inject mocks-PASS
2Mockito creates a mock instance of Calculator due to @Mock annotationCalculator mock object is created and ready-PASS
3Mockito creates an instance of CalculatorService and injects the Calculator mock into it because of @InjectMocksCalculatorService instance has its calculator field set to the mock Calculator-PASS
4Test method 'testAdd' runs: stub calculator.add(2, 3) to return 5Mock behavior defined: calculator.add(2, 3) returns 5-PASS
5Call calculatorService.add(2, 3), which internally calls mocked calculator.add(2, 3)calculatorService calls calculator mock, which returns 5Verify that calculatorService.add(2, 3) returns 5PASS
6Assert that the returned result equals 5 using assertEqualsAssertion compares expected 5 with actual 5assertEquals(5, result) passesPASS
Failure Scenario
Failing Condition: If @InjectMocks fails to inject the mock Calculator into CalculatorService, the calculator field is null
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @InjectMocks annotation do in this test?
AVerifies that the mock was called
BCreates a mock object of the class under test
CCreates an instance of the class under test and injects mocked dependencies
DStubs the method behavior of the mock
Key Result
Use @InjectMocks to automatically create the class under test and inject its mocked dependencies, simplifying setup and avoiding null references.