How to Use Spring Boot Test Slices Properly in Java
Use Spring Boot test slices properly: WebMvcTest, DataJpaTest, JsonTest and RestClientTest load only part of the context, with mocks, imports and speed gains.

@SpringBootTest starts the entire application context. That is the right tool for a few end-to-end tests and the wrong tool for most. Test slices load only the part of the context a test needs, and the difference shows in test time and in failure messages. Examples use Spring Boot 4 and JUnit 5.
The common slices
| Annotation | Loads | Use for |
|---|---|---|
@WebMvcTest | Controllers, advice, converters, filters | HTTP mapping, validation, status codes |
@DataJpaTest | Entities, repositories, JPA infrastructure | Queries and mappings |
@JsonTest | Jackson mappers | Serialisation formats |
@RestClientTest | RestClient, message converters, mock server | Outgoing HTTP clients |
@DataJdbcTest, @JdbcTest | JDBC repositories, JdbcTemplate | SQL code |
@WebFluxTest | Reactive controllers | WebFlux endpoints |
None of them load @Service or @Component beans except the ones that belong to the slice.
WebMvcTest
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService service;
@Test
void returnsOrder() throws Exception {
when(service.find(7L)).thenReturn(new OrderView(7L, "amy", 1999));
mvc.perform(get("/orders/7"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.customer").value("amy"));
}
@Test
void rejectsInvalidBody() throws Exception {
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isBadRequest());
}
}OrderService is not part of the slice, so the context would fail with a missing bean unless you mock it. @MockitoBean (the Spring Framework 6.2 replacement for @MockBean) registers a Mockito mock in the context. The test covers routing, binding, validation and error handling without a server or a database.
DataJpaTest
@DataJpaTest
class OrderRepositoryTest {
@Autowired OrderRepository repository;
@Autowired TestEntityManager em;
@Test
void findsByCustomer() {
em.persist(new Order("amy", 1999));
em.flush();
assertThat(repository.findByCustomer("amy")).hasSize(1);
}
}Each test runs in a transaction that rolls back. By default the slice replaces your data source with an embedded database. For a real database use Testcontainers and turn the replacement off:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(TestcontainersConfiguration.class)
class OrderRepositoryIT { ... }The embedded database may behave differently, see using H2 for tests and when not to.
Importing what the slice leaves out
If the controller depends on a mapper bean, a security configuration or a custom ObjectMapper module, the slice will not find it. Add it:
@WebMvcTest(OrderController.class)
@Import({OrderMapper.class, SecurityConfig.class})
class OrderControllerTest { ... }A missing import appears as NoSuchBeanDefinitionException or a security rule that differs from production. Read the message, then import the one missing configuration.
JsonTest
@JsonTest
class OrderViewJsonTest {
@Autowired JacksonTester<OrderView> json;
@Test
void serialises() throws Exception {
assertThat(json.write(new OrderView(7L, "amy", 1999)))
.extractingJsonPathStringValue("$.customer").isEqualTo("amy");
}
}This protects the API contract of serialisation cheaply.
Speed and context caching
Spring caches contexts across test classes with identical configuration. Each distinct combination of slice, mock beans and properties makes a new context, which is what slows suites. A slice context starts in a fraction of the full application's time. To keep the cache effective, avoid a unique set of @MockitoBean per class where one shared base would do, see caching the test context and keeping SpringBootTest fast.
Where full SpringBootTest still belongs
A handful of end-to-end tests should start the real application: one that checks the context wires, one per critical flow, one that checks security and error handling together. Everything finer is a slice or a plain unit test, see the layers in the test pyramid and unit versus integration tests.
Common mistakes
- Using
@SpringBootTestfor a controller test, then wondering why the suite takes minutes. - Putting
@ComponentScanon a configuration class used by the slice, which pulls in everything. - Forgetting that
@WebMvcTestincludes Spring Security, so requests needwith(user(...))andcsrf(), see 403 on POST. - Not mocking a dependency and getting a confusing bean error: failed to load ApplicationContext.
Choosing a slice by the layer under test
The annotation names map to layers, and picking the narrowest one that covers the behaviour keeps tests fast and failures local. Beyond the three covered above, Boot has a slice for most layers:
| Slice | Loads | Replaces what |
|---|---|---|
@WebMvcTest | Controllers, advice, filters, converters | Services, repositories (mock them) |
@DataJpaTest | Entities, repositories, an embedded or container database | Web layer, services |
@JdbcTest | JdbcTemplate and a data source | JPA, web |
@DataJdbcTest | Spring Data JDBC repositories | JPA, web |
@JsonTest | Jackson ObjectMapper and modules | Everything else |
@RestClientTest | RestClient or RestTemplate with a mock server | Real HTTP calls |
@WebFluxTest | Reactive controllers | Services and repositories |
A test of a JSON contract belongs in @JsonTest, and a test of a query belongs in @DataJpaTest. If a test needs a controller, a service and a repository together, it has outgrown the slices, and a full @SpringBootTest is the honest tool.
A rest client tested against a fake server
A client that calls another service is easy to leave untested. @RestClientTest supplies a mock server that returns canned responses and verifies the request:
@RestClientTest(RatesClient.class)
class RatesClientTest {
@Autowired RatesClient client;
@Autowired MockRestServiceServer server;
@Test
void parsesRate() {
server.expect(requestTo("/rates/EUR"))
.andRespond(withSuccess("{\"code\":\"EUR\",\"value\":1.08}", MediaType.APPLICATION_JSON));
assertThat(client.rate("EUR")).isEqualByComparingTo("1.08");
}
}The test checks both sides of the call: the URL the client builds and the way it reads the answer. It starts in a fraction of a second, with no network and no second service, and it fails when the remote JSON shape changes in a way the client cannot read.
Security in a web slice
A secured application loads the security filter chain in @WebMvcTest, and every request without credentials returns 401 or 403. Fix it with the test support instead of disabling security:
@WebMvcTest(OrderController.class)
class OrderControllerSecurityTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService service;
@Test
@WithMockUser(roles = "ADMIN")
void adminCanDelete() throws Exception {
mvc.perform(delete("/orders/1").with(csrf()))
.andExpect(status().isNoContent());
}
@Test
void anonymousIsRejected() throws Exception {
mvc.perform(delete("/orders/1").with(csrf()))
.andExpect(status().isUnauthorized());
}
}A test with @AutoConfigureMockMvc(addFilters = false) skips the filters, and it is the wrong default, since it removes the thing most worth testing. Keep one test per rule for allowed and denied.
See how many contexts the suite starts
The cache logs each hit and miss. Turn it on once to find out how many distinct contexts a suite creates:
logging.level.org.springframework.test.context.cache=DEBUGSearch the output for Storing ApplicationContext and count them. A suite with a dozen test classes and nine contexts has a configuration problem: different mock sets, properties or profiles per class. Merge them into a few shared bases. Cutting nine contexts to three typically halves the run time of an integration suite, and it costs a day of tidying once.
Mistakes that look like slice problems
| Symptom | Cause |
|---|---|
NoSuchBeanDefinitionException for a service | Slices do not load services, add @MockitoBean or @Import |
| A repository test hits a different database than production | @DataJpaTest replaces the data source, set replace = NONE and use a container |
| Slice picks up unrelated configuration | A @Configuration class in the scanned package, put it behind a profile |
| A test passes alone and fails with others | Shared state in a cached context |
The second row matters most. A query that works on H2 and fails on PostgreSQL is only found when the test uses PostgreSQL.
Naming and organising slice tests
A project with many tests benefits from a convention. Put each slice test next to the class it covers, named after it with a Test suffix, and use the narrowest annotation that works. Put shared configuration, such as a common set of mock beans, in a small base class or an importable configuration, so contexts are shared and the number of started contexts stays low. A package of end-to-end tests with @SpringBootTest sits apart, with a suffix such as IT that Failsafe picks up.
The convention makes it easy to run only the fast tests during development and the slower ones before a push.
When this does not apply
Plain unit tests of services need no Spring at all; use Mockito directly. References: Spring Boot testing and the test slice appendix.


