Testing Spring Boot: slice tests, integration tests and Testcontainers
What @WebMvcTest, @DataJpaTest and other slices load, @SpringBootTest with MockMvc or a real server, the @Transactional-in-tests traps, context caching, Testcontainers with @ServiceConnection, testing security with real JWTs, and the Spring Boot 4 testing changes, through a working lab.
On this page
Most bugs in a REST service live at the seams: wrong JSON mapping, validation that never runs, a query that fails on the real DB, security answering 500 instead of 403. This post tests those seams with slice tests, integration tests and Testcontainers while keeping the suite fast. Examples come from a Spring Boot 4.0.3 lab: mvn test runs 29 tests, 28 pass, 1 is skipped.
1. The problem
The delete-user API has @PreAuthorize("hasRole('ADMIN')"). The slice test passes. In production a regular user gets 200, and an admin deleting themselves gets 500 instead of 400. The slice doesn't load SecurityConfig, so no test saw either bug.
2. Key idea
Choose the test type by the question it must answer, not by habit. Slices are fast because they skip unrelated beans: @Service isn't loaded into @WebMvcTest; you supply it with @MockitoBean.
| Annotation | Loads | Answers |
|---|---|---|
| (Mockito only) | no Spring | business logic |
@WebMvcTest(X.class) |
controller, advice, Jackson, validation, default security | URLs, status, JSON, validation |
@DataJpaTest |
entities, repositories, DataSource | mapping, queries, constraints |
@SpringBootTest + MockMvc |
whole context, no server | the full flow through the real security chain |
@SpringBootTest(RANDOM_PORT) |
whole context + real Tomcat | cookies, container filters, thread switches |
2.1 Common traps
| Trap | Effect | Fix |
|---|---|---|
No flush() + clear() in @DataJpaTest |
rereads the in-memory object; wrong mappings still pass | always flush(), clear() before rereading |
IDENTITY ids |
save() already ran the INSERT; unique errors throw at save |
assertThatThrownBy(() -> repo.saveAndFlush(dup)) |
@Transactional on integration tests |
no rollback with RANDOM_PORT; hides LazyInitializationException; AFTER_COMMIT never runs |
commit for real, clean up data |
| Slice tests for authorization | slices use the default chain, not yours | @SpringBootTest with real JWTs |
A different @MockitoBean set per class |
each set is a new Spring context | share a base class, avoid @DirtiesContext |
2.2 What changed in Spring Boot 4?
- Test starters per module:
spring-boot-starter-webmvc-test,-data-jpa-test; slice packages moved accordingly. @MockBeanis gone; use@MockitoBean(available since Boot 3.4).- JUnit 6 (same Jupiter API);
RestTestClientadded.
3. In Java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // keep the datasource, no H2
@Testcontainers(disabledWithoutDocker = true)
class UserRepositoryPostgresTest {
@Container @ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine"); // pinned
@Autowired UserRepository users;
@Autowired TestEntityManager em;
@Test
void savesRolesThroughJoinTable() {
User u = users.save(new User("[email protected]", Set.of(role("HR"))));
em.flush(); em.clear(); // real SQL runs, the next read hits the DB
assertThat(users.findWithRolesById(u.getId()).orElseThrow().getRoles())
.extracting(Role::getName).containsExactly("HR");
}
}One shared container: declare it as @Bean @ServiceConnection in a @TestConfiguration and @Import it everywhere. Other languages: Testcontainers exists for Go, Node.js, .NET and Python.
Authorization tests with real JWTs
The integration test signs tokens with the app's own JwtEncoder, creates users with exactly the permissions the test needs, then checks:
| Scenario | Expected |
|---|---|
| wrong password, no token, tampered signature | 401, WWW-Authenticate: Bearer, application/problem+json |
| role missing the permission | 403 |
missing ADMIN on a @PreAuthorize method |
403 |
| reusing an old refresh token | 401 and the whole family revoked |
@PreAuthorize throws AccessDeniedException inside the controller, so an advice with @ExceptionHandler(Exception.class) swallows it and returns 500. You only see this with the real advice, real method security and the real chain together.
4. Working with AI
Give the AI: @WebMvcTest skeletons for every endpoint, an authorization test matrix, shared Testcontainers config.
Check in AI-written code:
-
@DataJpaTestcallsflush()+clear()before rereading. - No
@TransactionalonRANDOM_PORTtests or key flow tests. - Authorization is tested with
@SpringBootTest, not slices. - No
@MockBean, no unexplained@DirtiesContext. - Testcontainers images have pinned versions, never
latest.
5. Exercises
Exercise 1: "Authorization tested"
The AI writes a @WebMvcTest(UserController.class) with @WithMockUser(roles = "USER") calling DELETE /api/v1/users/2, expecting 403, noted as "authorization tested". It fails: 200. The AI suggests adding @EnableMethodSecurity to the test. What do you think?
Solution to Exercise 1
The slice doesn't load SecurityConfig (it needs a @Component the slice skips), so @PreAuthorize has no effect. Adding @EnableMethodSecurity makes the test pass but still doesn't exercise your real chain (URL rules, the roles converter).
Keep the slice for error mapping and JSON. Move authorization tests to @SpringBootTest + MockMvc with JWTs signed by the app's JwtEncoder: regular user 403, admin 204, admin deleting themselves 400.
Exercise 2: Suite went from 2 to 9 minutes
org.springframework.test.context.cache=DEBUG reports 14 contexts for 40 test classes. Each class declares its own @MockitoBeans and three use @DirtiesContext. How do you fix it?
Solution to Exercise 2
Every different set of @MockitoBean, @TestPropertySource, profiles or @Import is a different cache key, meaning one more app startup (and maybe one more container). @DirtiesContext throws the context away.
Fix: one base class for integration tests with the same @MockitoBeans (mock only external systems) and the same @Import(PostgresConfig.class); replace @DirtiesContext with data cleanup in @BeforeEach. Target: one context for @SpringBootTest, one for @DataJpaTest. Move integration tests to failsafe (*IT.java) to run them in parallel on CI.
Summary
- Choose the test type by the question it must answer.
- Slices don't prove authorization; use
@SpringBootTestwith real JWTs. flush()+clear()in@DataJpaTest.@Transactionalon integration tests hides bugs.- Keep
@MockitoBeansets identical; share one container.
Read more: Unit testing with JUnit and Mockito.
Practice interview questions on this topic
- How do @WebMvcTest and @DataJpaTest differ from @SpringBootTest, and @MockitoBean from @Mock?
- For database integration tests, when do you use H2 vs Testcontainers, and should you roll back with @Transactional?
- The team's Spring Boot test suite takes 15 minutes. How do you investigate and speed it up?
- What is Docker Compose for, and how do you write a compose file for Spring Boot + PostgreSQL + Redis?
Comments
Community rules