0
0
JUnittesting~10 mins

@MockBean for Spring mocking in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies that a Spring service method returns the expected value by mocking a dependency using @MockBean. It checks that the service uses the mocked repository correctly.

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

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

@SpringBootTest
class UserServiceTest {

    @MockBean
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Test
    void testGetUserNameById() {
        // Arrange
        when(userRepository.findNameById(1L)).thenReturn("Alice");

        // Act
        String name = userService.getUserNameById(1L);

        // Assert
        assertEquals("Alice", name);
    }
}

// Supporting classes
interface UserRepository {
    String findNameById(Long id);
}

class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public String getUserNameById(Long id) {
        return userRepository.findNameById(id);
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes Spring context with @MockBean replacing UserRepository bean-PASS
2Spring injects mocked UserRepository into UserServiceUserService bean uses mocked UserRepository-PASS
3Test sets up mock behavior: when findNameById(1L) called, return 'Alice'Mock configured to return 'Alice' for id 1-PASS
4Test calls userService.getUserNameById(1L)UserService calls mocked UserRepository.findNameById(1L)-PASS
5Mock returns 'Alice' as configuredMethod returns 'Alice'Check that returned name equals 'Alice'PASS
6Test asserts returned name is 'Alice'Assertion compares expected 'Alice' with actual 'Alice'assertEquals('Alice', name)PASS
7Test finishes successfullyTest passes with no errors-PASS
Failure Scenario
Failing Condition: Mock behavior not set or returns null, causing assertion to fail
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @MockBean annotation do in this test?
AInjects UserService into UserRepository
BReplaces the UserRepository bean with a mock in the Spring context
CCreates a real instance of UserRepository
DRuns the test without Spring context
Key Result
Using @MockBean in Spring tests allows you to replace real beans with mocks easily, so you can control dependencies and test service logic in isolation.