Testing in Spring Boot series: 1. Unit testing with JUnit and Mockito · 2. Slice tests and Testcontainers
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 shows how to test those seams with slice tests, integration tests and Testcontainers while keeping the suite fast. Every example comes from a Spring Boot 4.0.3 lab: mvn test runs 29 tests, 28 pass, 1 is skipped.
At a glance:
flowchart TD
A{"Which question?"} -->|"HTTP layer"| C["@WebMvcTest"]
A -->|"Repository and SQL"| D["@DataJpaTest + flush/clear"]
A -->|"Whole flow"| E["@SpringBootTest"]
E --> F{"Need real HTTP?"}
F -->|"No"| G["MockMvc"]
F -->|"Yes"| H["RANDOM_PORT"]
D --> I["Testcontainers + @ServiceConnection"]
E --> I
I --> J["Few configs, cached context"]
1. A map of Spring Boot test types
Key idea: pick the test type by the question you need answered, not by habit. Slices answer questions about one layer; @SpringBootTest answers questions about the whole flow.
| Annotation | Loads | Answers |
|---|---|---|
| (nothing, just Mockito) | no Spring | is the business logic right (part 1) |
@WebMvcTest(XController.class) |
that controller, @ControllerAdvice, Jackson, validation, filters, Spring Security |
URLs, status codes, JSON, validation, error mapping |
@DataJpaTest |
entities, repositories, EntityManager, DataSource (embedded DB by default) |
mappings, queries, constraints |
@JsonTest |
Jackson ObjectMapper and JacksonTester |
date formats, field names, @JsonInclude |
@SpringBootTest + @AutoConfigureMockMvc |
full context, no real server | full flow through the real security chain |
@SpringBootTest(webEnvironment = RANDOM_PORT) |
full context + real server | real HTTP behaviour: container filters, cookies, thread hops |
Slices are fast because they skip unrelated beans. Ordinary @Service and @Component beans are not loaded into @WebMvcTest; you supply them with @MockitoBean.
2. @WebMvcTest: testing the HTTP layer
Key idea: @WebMvcTest checks what a unit test can’t see: URLs mapped to the right method, @Valid actually running, JSON with the right fields, exceptions mapped to the right status. The service is replaced by a @MockitoBean.
@WebMvcTest(UserController.class)
class UserControllerWebMvcTest {
@Autowired MockMvc mvc;
@MockitoBean UserService userService;
@Test
@WithMockUser
void invalidBodyReturnsProblemDetailWithAllFieldErrors() throws Exception {
mvc.perform(post("/api/v1/users").with(csrf()).contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":" ","email":"not-an-email","password":"123"}"""))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.errors[*].field", hasItem("email")));
verify(userService, never()).create(any());
}
}
The four tests in the lab check: 201 + a Location header + no password field; 400 with all field errors; DuplicateResourceException → 409; malformed JSON → 400, not 500.
3. @DataJpaTest: testing repositories against a DB
Key idea: @DataJpaTest runs JPA against an embedded DB, each test in a transaction that is rolled back. To see real SQL and real errors, call flush() to push SQL to the DB and clear() so the next read doesn’t come from the persistence context.
@Test
void replaceKeepsPermissionsRowsAndRewritesJoinTable() {
Permission a = permissions.save(new Permission("A", "/api/v1/a", "GET", "X"));
Permission b = permissions.save(new Permission("B", "/api/v1/b", "GET", "X"));
Role r = new Role("HR");
r.getPermissions().add(a);
roles.save(r);
em.flush(); em.clear(); // force real SQL, otherwise we only test the 1st-level cache
Role loaded = roles.findWithPermissionsById(r.getId()).orElseThrow();
loaded.replacePermissions(Set.of(permissions.getReferenceById(b.getId())));
em.flush(); em.clear();
Role again = roles.findWithPermissionsById(r.getId()).orElseThrow();
assertThat(again.getPermissions()).extracting(Permission::getName).containsExactly("B");
assertThat(permissions.count()).isEqualTo(2); // A still exists, only the link is gone
}
Without clear(), findWithPermissionsById hands back the very object in memory, and the test is green even if the join-table mapping is wrong. The persistence context and first-level cache are covered in JPA persistence context and N+1.
4. @SpringBootTest: MockMvc or a real server
Key idea: @SpringBootTest + MockMvc loads the whole context and goes through the real security chain, but the request runs on the test’s thread with no server. RANDOM_PORT starts a real Tomcat and sends real HTTP; slower, but closer to production.
MockMvc (MOCK) |
RANDOM_PORT + RestTestClient / TestRestTemplate |
|
|---|---|---|
| Server | none, calls DispatcherServlet directly |
real Tomcat on a random port |
| Thread | same thread as the test | a server thread |
@Transactional on the test |
can roll back the request | does not roll back (different thread) |
| Can check | controllers, Spring filters, security | plus: container filters, real cookies, timeouts, encoding |
RestTestClient is the new test client in Spring Framework 7, usable with MockMvc or a live server. TestRestTemplate still exists in Boot 4 but moved to its own module; the course saying it was “replaced” isn’t accurate.
5. Testing security with real JWTs
Key idea: authorization integration tests should use real tokens, signed by the application’s own JwtEncoder, going through the real filter chain. A TestDataFactory creates users with exactly the permissions each test needs and issues tokens for them.
@TestComponent
public class TestDataFactory {
// ... repositories, PasswordEncoder, JwtService via constructor
public void reset() {
tokens.deleteAll(); users.deleteAll(); roles.deleteAll(); permissions.deleteAll();
}
/** permissionSpecs like "GET /api/v1/users/{id}". Empty = a role with no permission. */
public User user(String email, String password, String roleName, String... permissionSpecs) { ... }
public String accessToken(User u, String roleName) {
return jwt.issueAccessToken(u.getEmail(), List.of(roleName));
}
}
The scenarios in AuthFlowIntegrationTest (12 tests, grouped with @Nested):
| Group | Scenario | Expected |
|---|---|---|
| Authentication | wrong password; no token; tampered signature | 401, with WWW-Authenticate: Bearer, body application/problem+json |
| Authorization | role with a permission matching the path pattern; empty role | 200; 403 |
| MethodSecurity | URL permission but no ADMIN role; ADMIN deleting himself | 403 from @PreAuthorize; 400 |
| RefreshRotation | rotation; reusing an old token; logout; missing cookie | new token; 401 and whole family revoked; cookie Max-Age=0; 401 |
This post only covers how to test. Resource-server configuration is explained in Spring Security for REST APIs, refresh-token rotation and the permission-based AuthorizationManager in rotating refresh tokens and permission-based authorization; JWT theory is in the authentication post.
The full AuthFlowIntegrationTest (repetition trimmed)
@SpringBootTest
@AutoConfigureMockMvc
@Import(TestDataFactory.class)
class AuthFlowIntegrationTest {
@Autowired MockMvc mvc;
@Autowired TestDataFactory data;
@Autowired RefreshTokenRepository tokens;
User admin;
@BeforeEach
void setUp() {
data.reset();
admin = data.user("admin@example.dev", "secret-pass-1", "ADMIN", "GET /api/v1/users/{id}", "POST /api/v1/users");
}
@Nested
class Authorization {
@Test
void permissionMatchingPathPatternIs200() throws Exception {
mvc.perform(get("/api/v1/users/" + admin.getId())
.header("Authorization", "Bearer " + data.accessToken(admin, "ADMIN")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.email").value("admin@example.dev"));
}
@Test
void roleWithoutPermissionIs403() throws Exception {
User viewer = data.user("viewer@example.dev", "secret-pass-1", "VIEWER");
mvc.perform(get("/api/v1/users/" + admin.getId())
.header("Authorization", "Bearer " + data.accessToken(viewer, "VIEWER")))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.status").value(403));
}
}
@Nested
class RefreshRotation {
@Test
void reusingARotatedTokenRevokesTheWholeFamily() throws Exception {
String first = login();
String second = mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", first)))
.andReturn().getResponse().getCookie("refresh_token").getValue();
mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", first)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.detail").value("refresh token reuse detected"));
// the legitimate user's newest token died with the family (revocation committed despite the 401)
mvc.perform(post("/api/v1/auth/refresh").cookie(new Cookie("refresh_token", second)))
.andExpect(status().isUnauthorized());
assertThat(tokens.findAll()).allMatch(RefreshToken::isRevoked);
}
}
}
The last test only works because the test is not @Transactional: the service uses noRollbackFor so the family revocation commits even though it answers 401, and the test checks that by reading back from the DB.
In @WebMvcTest, when you don’t need a real token, use the spring-security-test post-processor: .with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))) builds a JwtAuthenticationToken without signing anything.
6. Testcontainers: a real DB in Docker
Key idea: Testcontainers starts a real PostgreSQL/MySQL in Docker for your tests; @ServiceConnection (Boot 3.1+) lets Boot read URL, user and password from the container. The test catches differences that H2 hides.
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // keep our datasource, don't swap in H2
@Testcontainers(disabledWithoutDocker = true) // no Docker on the machine: skipped, not failed
class UserRepositoryPostgresTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");
@Autowired UserRepository users;
@Test
void uniqueEmailIsCaseSensitiveInPostgresSoTheServiceMustNormalize() {
users.saveAndFlush(new User("A", "an@example.dev", "h", User.Gender.OTHER));
users.saveAndFlush(new User("B", "AN@example.dev", "h", User.Gender.OTHER)); // UNIQUE compares bytes, not "emails"
assertThat(users.count()).isEqualTo(2);
assertThat(users.existsByEmailIgnoreCase("An@Example.DEV")).isTrue();
}
}
Actual status: this test compiles but was skipped when I ran the suite, because the Docker engine on my machine was stopped. The outcome it asserts (PostgreSQL stores two emails that differ only in case) is the known behaviour of UNIQUE on varchar with the default collation, not confirmed by this run.
Why to prefer the real DB over H2 (syntax, date functions, locking, collation) is already a trade-off in the Spring Boot implementation plan post; not repeated here.
Keeping Testcontainers fast: one container for the whole suite
- A static container in a shared abstract class, or a
@TestConfigurationdeclaring@Bean @ServiceConnection PostgreSQLContainer: every test class sharing the context shares one container instead of one per class. - Start once per JVM: declare the container in a
static {}block and callstart(); Ryuk cleans it up when the JVM exits. - Reuse across local runs:
withReuse(true)+testcontainers.reuse.enable=truein~/.testcontainers.properties; not on CI. - Small, pinned images:
postgres:17-alpine, neverlatest, so tests don’t change behaviour when a new image ships. - Run locally against containers: Boot 3.1+ lets a
TestApplicationcallSpringApplication.from(App::main).with(ContainersConfig.class).run(args)to run the dev app with a DB in Docker. - Testcontainers 2.x (with Boot 4): artifacts renamed to
testcontainers-postgresql,testcontainers-junit-jupiter, and the PostgreSQL class lives in the new packageorg.testcontainers.postgresql. - If your Docker isn’t on the default socket (Colima, OrbStack…), set
DOCKER_HOSTordocker.hostin~/.testcontainers.properties.
7. Keeping the suite fast: context caching
Key idea: Spring caches the application context between test classes with the same configuration. Every difference (set of @MockitoBean, @TestPropertySource, profile, @Import) creates a new cache key and a new context startup.
- Gather
@MockitoBeans in a base class or keep them identical across tests of the same kind. - Avoid
@DirtiesContext; it throws the context away and forces a restart. There’s usually a cheaper way to clean data. - Turn on
org.springframework.test.context.cache=DEBUGlogging to see how many contexts were created and the hit rate. - The cache holds at most 32 contexts by default (
spring.test.context.cache.maxSize); an evicted context is closed, and a container bound to it may stop too. - Split groups: unit and slice tests run on every build (
surefire); integration tests with Testcontainers can move tofailsafe(*IT.java) and run in parallel on CI. A GitHub Actions pipeline that runs both groups with./mvnw verify, Testcontainers included, is in CI/CD for a Spring Boot backend.
8. Testing changes in Spring Boot 4
Key idea: Boot 4 splits test annotations by module and needs a test starter per technology; @MockBean is gone. Old test code usually only needs new imports and dependencies.
| Change | Boot 3.x | Boot 4 |
|---|---|---|
| Test starter | one spring-boot-starter-test |
plus spring-boot-starter-webmvc-test, -data-jpa-test, -security-oauth2-resource-server-test… (they include starter-test) |
| Slice package | org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest |
org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; @DataJpaTest in ...boot.data.jpa.test.autoconfigure |
| Mock bean | @MockBean (deprecated since 3.4) |
@MockitoBean, @MockitoSpyBean (Spring Framework, since 6.2 / Boot 3.4) |
| JUnit | 5 | 6 (Jupiter API unchanged) |
| HTTP test client | TestRestTemplate, WebTestClient |
plus RestTestClient; TestRestTemplate still exists in its own module |
Exercises
- Write a
@WebMvcTestfor the lab’sDELETE /api/v1/users/{id}proving that whenUserService.deletethrowsIllegalArgumentException, the API answers 400 withapplication/problem+json. Do you need@EnableMethodSecurityin the slice? - Redesign the lab’s suite so every integration test runs on PostgreSQL via Testcontainers with one shared container, and count how many Spring contexts get created.
Suggested solutions
Exercise 1. The slice doesn’t load SecurityConfig, so @EnableMethodSecurity isn’t active and @PreAuthorize("hasRole('ADMIN')") is ignored: this test checks error mapping only, not permissions.
@Test
void selfDeleteIs400() throws Exception {
doThrow(new IllegalArgumentException("You cannot delete your own account"))
.when(userService).delete(eq(1L), any());
mvc.perform(delete("/api/v1/users/1").with(jwt()).with(csrf()))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON));
}
jwt() provides an Authentication so the controller gets its auth parameter. To check @PreAuthorize inside a slice, @Import a tiny config with @EnableMethodSecurity; but the real permission check is already covered by AuthFlowIntegrationTest.
Exercise 2. Create @TestConfiguration(proxyBeanMethods = false) class PostgresConfig with @Bean @ServiceConnection PostgreSQLContainer postgres(); every @SpringBootTest shares @Import(PostgresConfig.class) and adds no @MockitoBean of its own, so there is one context and one container. @DataJpaTest is a different configuration and gets its own context (plus a container if it imports this config too). Count contexts with org.springframework.test.context.cache=DEBUG logging. This solution was not run, because the Docker engine on the machine was stopped.
Remember
- Choose between unit,
@WebMvcTest,@DataJpaTestand@SpringBootTestby the question you need answered. - Explain why a slice test doesn’t prove authorization rules, and how to test them instead.
- Know why
@DataJpaTestneedsflush()/clear(), and why withIDENTITYa constraint error is thrown atsave. - Name three bugs that
@Transactionalon an integration test hides. - Explain context caching and how to keep a Testcontainers suite fast.
Interview questions
Mid
How does @WebMvcTest differ from @SpringBootTest?
@WebMvcTest loads only the web layer (controller, advice, Jackson, validation, security) and mocks the rest; @SpringBootTest loads the whole application.
The slice is fast and pinpoints HTTP-layer bugs. @SpringBootTest is slower but checks the real flow through your services, DB and security chain.
Why call flush() and clear() in a @DataJpaTest?
flush() pushes SQL to the DB so real constraints and mappings run; clear() empties the persistence context so the next read hits the DB instead of returning the object in memory.
Without them a test can be green with a wrong mapping, because you just read back the object you saved.
What is the difference between @MockitoBean and @Mock?
@Mock is a plain Mockito mock in a unit test; @MockitoBean replaces a bean in the Spring context with a mock.
Use @MockitoBean in slice/integration tests. Each distinct set of @MockitoBeans makes Spring build a new context, so use them sparingly.
Senior
Should you put @Transactional on integration tests to roll back data?
With MockMvc it works but hides bugs; with RANDOM_PORT it does nothing. Important tests should really commit and clean up themselves.
@Transactional on the test keeps a transaction open throughout, hiding LazyInitializationException, commit-time errors and AFTER_COMMIT listeners. With a real server the request runs on another thread, so nothing is rolled back. Clean data in @BeforeEach or use unique data per test instead.
The team’s Spring Boot test suite takes 15 minutes. How do you investigate?
First count how many Spring contexts get created: the context-cache log shows how many startups happen and why.
- Align
@MockitoBeans, properties and profiles so classes share a context; remove@DirtiesContext. - One shared Testcontainers container instead of one per class.
- Push logic down to unit tests; move integration tests to
failsafeand run them in parallel on CI.
How do you test authorization in a REST API that uses JWT?
With @SpringBootTest + MockMvc and real tokens signed by the app’s own JwtEncoder, through the real filter chain, for users holding exactly the permissions each test needs.
Cover 401 (no token, broken token, expired), 403 (missing permission, missing role for method security) and 200. A slice test with jwt() or @WithMockUser proves the controller, not the rules.
When do you choose H2, and when Testcontainers?
Testcontainers with the production DB for anything touching queries, constraints or locking; H2 only when you need raw speed for simple mappings and accept the dialect risk.
H2 differs in syntax, date functions, collation and locking behaviour. The cost of Testcontainers is needing Docker and startup time, reduced with a shared container.
Useful phrases for interviews
- “A slice test proves the controller; it doesn’t prove the authorization rules.”
- “I flush and clear the persistence context so the test hits real SQL.”
- “With identity ids, Hibernate inserts on persist, so the constraint violation shows up at save.”
- “A transactional test hid our LazyInitializationException; production didn’t.”
- “With a random port, the test transaction can’t roll back the server’s work.”
- “Every distinct set of mocked beans is a new application context.”
- “With a service connection, Boot reads the JDBC URL straight from the container.”
- “We sign test tokens with the application’s own encoder, so they go through the real filter chain.”
- “Our integration tests use one shared Postgres container for the whole suite.”
- “MockitoBean replaced MockBean in Boot 3.4, and Boot 4 removed MockBean entirely.”
Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.