|
| 1 | +# ADR-008: Use `@SpringBootTest` Instead of `@MockMvc` |
| 2 | + |
| 3 | +Date: 2025-10-23 |
| 4 | + |
| 5 | +## Status |
| 6 | + |
| 7 | +Accepted |
| 8 | + |
| 9 | +## Context |
| 10 | + |
| 11 | +In the current project, integration tests are written using both `@SpringBootTest` and `@MockMvc`. |
| 12 | +While `@MockMvc` is useful for testing specific layers (e.g., controllers) in isolation, it does not |
| 13 | +load the full application context. This can lead to inconsistencies when testing features that rely |
| 14 | +on the complete Spring Boot configuration. A unified approach is needed to ensure reliable and |
| 15 | +consistent integration testing. |
| 16 | + |
| 17 | +## Decision |
| 18 | + |
| 19 | +The project will use `@SpringBootTest` for all integration tests. This ensures that the full |
| 20 | +application context is loaded, providing a more comprehensive testing environment. While `@MockMvc` |
| 21 | +will no longer be used for integration tests, alternatives such as `TestRestTemplate` or |
| 22 | +`WebTestClient` can be considered for specific scenarios. |
| 23 | + |
| 24 | +## Alternatives |
| 25 | + |
| 26 | +1. **`@MockMvc`**: |
| 27 | + - **Pros**: |
| 28 | + - Faster as it does not load the full application context. |
| 29 | + - Useful for testing controllers in isolation. |
| 30 | + - **Cons**: |
| 31 | + - Limited to the web layer. |
| 32 | + - Does not test the full application behavior. |
| 33 | + |
| 34 | +2. **`TestRestTemplate`**: |
| 35 | + - **Pros**: |
| 36 | + - Provides a way to test REST endpoints with the full application context. |
| 37 | + - **Cons**: |
| 38 | + - Slower than `@MockMvc`. |
| 39 | + |
| 40 | +3. **`WebTestClient`**: |
| 41 | + - **Pros**: |
| 42 | + - Non-blocking and supports reactive applications. |
| 43 | + - **Cons**: |
| 44 | + - Requires additional setup for non-reactive applications. |
| 45 | + |
| 46 | +## Consequences |
| 47 | + |
| 48 | +- **Positive**: |
| 49 | + - Ensures consistent testing by loading the full application context. |
| 50 | + - Tests the application as a whole, including configuration and dependencies. |
| 51 | + - Reduces the need for mocking in integration tests. |
| 52 | + |
| 53 | +- **Negative**: |
| 54 | + - Slower test execution due to the full context initialization. |
| 55 | + - May require additional resources for running tests. |
| 56 | + |
| 57 | +## Implementation |
| 58 | + |
| 59 | +1. Replace `@MockMvc` with `@SpringBootTest` in all integration tests: |
| 60 | + ```java |
| 61 | + @SpringBootTest |
| 62 | + public class ExampleIntegrationTest { |
| 63 | + |
| 64 | + @Autowired |
| 65 | + private TestRestTemplate restTemplate; |
| 66 | + |
| 67 | + @Test |
| 68 | + public void testEndpoint() { |
| 69 | + ResponseEntity<String> response = restTemplate.getForEntity("/example", String.class); |
| 70 | + assertEquals(HttpStatus.OK, response.getStatusCode()); |
| 71 | + } |
| 72 | + } |
0 commit comments