0 day streak
java / beginner
Snippet

Simulating Dependency Behavior in Spring Integration Tests

In Spring Boot tests, @MockBean replaces an actual Spring bean in the application context with a Mockito mock instance. This allows you to define simulated return values for dependencies and verify individual component behavior without invoking real external systems or databases.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
void shouldReturnDefaultStatus() {
when(userRepository.findStatus(1L)).thenReturn("ACTIVE");
String status = userService.getUserStatus(1L);
assertEquals("ACTIVE", status);
}
}
spring
Breakdown
1
@MockBean private UserRepository userRepository;
Creates and registers a Mockito mock of the repository in the Spring context.
2
when(userRepository.findStatus(1L)).thenReturn("ACTIVE");
Configures the mock to return a predefined string value whenever the method is called with ID 1.