0 day streak
java / beginner
Snippet

Mocking Service Dependencies in Spring Unit Tests

Unit testing Spring components requires isolating business logic from external systems like databases. Using Mockito with JUnit 5 enables mocking dependencies via @Mock and automatically injecting them into the target class under test using @InjectMocks.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void testFindUserById() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("Alice")));
User user = userService.getUser(1L);
assertEquals("Alice", user.getName());
}
}
spring
Breakdown
1
@ExtendWith(MockitoExtension.class)
Initializes the Mockito framework for JUnit 5 test lifecycle management.
2
@Mock private UserRepository userRepository;
Creates a mocked instance of the repository dependency.
3
@InjectMocks private UserService userService;
Instantiates the UserService and injects the created mocks into it.
4
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("Alice")));
Stubs the mock repository method to return a predefined User instance when queried with ID 1.