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.
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.
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); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes Spring context with @MockBean replacing UserRepository bean | - | PASS |
| 2 | Spring injects mocked UserRepository into UserService | UserService bean uses mocked UserRepository | - | PASS |
| 3 | Test sets up mock behavior: when findNameById(1L) called, return 'Alice' | Mock configured to return 'Alice' for id 1 | - | PASS |
| 4 | Test calls userService.getUserNameById(1L) | UserService calls mocked UserRepository.findNameById(1L) | - | PASS |
| 5 | Mock returns 'Alice' as configured | Method returns 'Alice' | Check that returned name equals 'Alice' | PASS |
| 6 | Test asserts returned name is 'Alice' | Assertion compares expected 'Alice' with actual 'Alice' | assertEquals('Alice', name) | PASS |
| 7 | Test finishes successfully | Test passes with no errors | - | PASS |