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.
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.
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); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test framework initializes and processes @ExtendWith(MockitoExtension.class) to enable Mockito support | MockitoExtension is active, ready to process mocks and inject mocks | - | PASS |
| 2 | Mockito creates a mock instance of Calculator due to @Mock annotation | Calculator mock object is created and ready | - | PASS |
| 3 | Mockito creates an instance of CalculatorService and injects the Calculator mock into it because of @InjectMocks | CalculatorService instance has its calculator field set to the mock Calculator | - | PASS |
| 4 | Test method 'testAdd' runs: stub calculator.add(2, 3) to return 5 | Mock behavior defined: calculator.add(2, 3) returns 5 | - | PASS |
| 5 | Call calculatorService.add(2, 3), which internally calls mocked calculator.add(2, 3) | calculatorService calls calculator mock, which returns 5 | Verify that calculatorService.add(2, 3) returns 5 | PASS |
| 6 | Assert that the returned result equals 5 using assertEquals | Assertion compares expected 5 with actual 5 | assertEquals(5, result) passes | PASS |