Sub topic 7
Test slices: loading only what you need
Prerequisites
This chapter assumes you can write a basic @SpringBootTest and know what a Spring bean is. It also assumes you have used JUnit 5 and Mockito. You should know that @SpringBootTest loads the whole application context, which is the object that holds every bean in the application.
The problem slices solve
A full @SpringBootTest starts every bean: controllers, services, repositories, security, schedulers, message listeners and more. That is slow, and it fails for reasons unrelated to the code under test. A controller test should not break because the database is down.
A test slice loads a narrow part of the application and nothing else. Each slice annotation does two things:
- It restricts component scanning to the bean types that belong to that layer.
- It applies only the auto-configuration that layer needs.
The result is a smaller context that starts faster and tests one concern.
How a slice decides what to load
Slice annotations are meta-annotations. Each one combines three pieces:
@BootstrapWith(SpringBootTestContextBootstrapper.class), which makes Spring Boot's test support build the context.- A type-exclude filter. It tells component scanning to include only certain beans. For
@WebMvcTestthese are@Controller,@ControllerAdvice,@JsonComponent,Converter,Filter,WebMvcConfigurerand similar types. Plain@Component,@Serviceand@Repositorybeans are skipped. @AutoConfigureXxxand@ImportAutoConfigurationannotations. They enable only the auto-configurations for that layer, such asMockMvcfor web tests or Hibernate and Spring Data for JPA tests.
The slice still finds your @SpringBootApplication class by searching up the package tree, the same way @SpringBootTest does. That class's own configuration is therefore part of every slice. This matters in the gotchas below.
Common slices
| Annotation | Loads | Does not load | Typical use |
|---|---|---|---|
| `@WebMvcTest` | Controllers, advice, filters, converters, `MockMvc` | Services, repositories | Request mapping, validation, status codes, JSON output |
| `@DataJpaTest` | Entities, Spring Data repositories, `EntityManager`, `TestEntityManager` | Controllers, services | Queries, mappings, constraints |
| `@JsonTest` | Jackson `ObjectMapper`, `JacksonTester` | Everything else | Serialization and deserialization |
| `@RestClientTest` | `RestClient` or `RestTemplate` builders, `MockRestServiceServer` | Controllers, repositories | Code that calls other HTTP services |
| `@WebFluxTest` | Reactive controllers, `WebTestClient` | Services, repositories | Reactive web layer |
| `@DataJdbcTest`, `@JdbcTest`, `@DataMongoTest`, `@DataRedisTest` | The matching data layer | Web and service beans | Persistence with that technology |
The last two chapters of this tutorial cover @JsonTest and @RestClientTest in more detail. The next chapters cover @WebMvcTest and @DataJpaTest.
A slice in practice
This controller depends on a service. In a slice test, the service does not exist unless you provide it.
@RestController
class GreetingController {
private final GreetingService service;
GreetingController(GreetingService service) {
this.service = service;
}
@GetMapping("/greetings/{name}")
String greet(@PathVariable String name) {
return service.greetingFor(name);
}
}If you write @WebMvcTest(GreetingController.class) and nothing else, the context fails to start with an error such as No qualifying bean of type 'GreetingService' available. The slice skipped GreetingService because it is a plain @Service. This failure is the slice working as designed. You must decide how to fill the gap:
- Replace the collaborator with a mock using
@MockitoBean(@MockBeanbefore Spring Boot 3.4). This is the usual choice for a web test. - Import the real class with
@Import(GreetingService.class)when the real logic is small and you want it included. - Add a
@TestConfigurationclass that defines a stub bean.
@WebMvcTest(GreetingController.class)
class GreetingControllerTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
GreetingService service;
@Test
void returnsGreeting() throws Exception {
when(service.greetingFor("Ada")).thenReturn("Hello, Ada");
mockMvc.perform(get("/greetings/Ada"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Ada"));
}
}The test covers request mapping, path variable binding and response writing. It does not touch a database or a real service.
Choosing and narrowing a slice
Pass a controller class to @WebMvcTest to load only that controller. Without an argument, every controller in the application is loaded, and each needs its dependencies mocked. Naming the controller keeps the mock list short.
You can also adjust a slice without leaving it:
@Importadds specific beans, such as a validator or a mapper.@AutoConfigureXxxannotations switch on extra features. For example,@AutoConfigureJsonTestersadds JSON tester support to a test that did not get it by default.includeFiltersandexcludeFilterson the slice annotation change what scanning picks up. Use them sparingly, because they make the slice harder to read.
Common errors and gotchas
A missing bean after you upgrade a slice
Symptom: NoSuchBeanDefinitionException for a service, repository or custom component. Cause: the slice does not scan that bean type. Fix: mock it, import it, or move the test to a wider slice.
Slices that load too much because of the application class
Component scanning, @EnableXxx annotations and custom beans placed directly on the @SpringBootApplication class are processed in every slice. Suppose you put @EnableScheduling, @EnableJpaRepositories or a @Bean method that needs a database on that class. A @WebMvcTest then tries to start the scheduler or set up JPA, and it fails or slows down.
The fix is to move that configuration into its own @Configuration class. Slices do not scan plain @Configuration classes by default through their filter, so they stay out of the way. For example, put @EnableJpaRepositories on a PersistenceConfig class rather than on the application class.
Security filters change your results
If Spring Security is on the classpath, @WebMvcTest includes its auto-configuration, so requests without credentials return 401 or 403. This is expected. The security testing chapter shows how to add test users and CSRF tokens.
`@DataJpaTest` swaps your database
By default @DataJpaTest replaces the configured DataSource with an embedded database such as H2 and runs each test in a transaction that rolls back. If your production database is PostgreSQL, an embedded database can hide dialect and constraint differences. Add @AutoConfigureTestDatabase(replace = NONE) and point the test at a real database, as the Testcontainers chapter does.
Using the wrong tool for the question
A slice test verifies one layer in isolation. It will not catch a wrong wiring between layers, such as a service that never calls the repository method you mocked. Keep a small number of @SpringBootTest tests for end-to-end paths.
Choosing between a unit test, a slice and a full test
| Question | Best level |
|---|---|
| Does this method compute the right result? | Unit test with no Spring |
| Does the URL, validation and JSON for this endpoint work? | `@WebMvcTest` |
| Does this query return the right rows? | `@DataJpaTest` |
| Does this class serialize to the expected JSON? | `@JsonTest` |
| Do all the layers work together? | `@SpringBootTest` |
Pick the cheapest level that can fail for the reason you care about. If a plain unit test can catch the bug, use it. If you need Spring's request handling or persistence, use a slice. Use the full context only when the question is about the whole.
Slices and the context cache
Spring caches each context it builds and reuses it for later test classes with the same configuration. Each distinct slice annotation, @MockitoBean set, @Import list and property override produces a different cache key. Ten web tests that each mock a different bean produce ten contexts. To keep reuse high, mock the same set of beans across web test classes, or put shared mocks in a common base class or @TestConfiguration. A later chapter covers the cache in detail.
Exercise
A @WebMvcTest(OrderController.class) fails at startup with "No qualifying bean of type 'OrderService'". Name two ways to fix it, and say which you would choose when the test only checks that an invalid request body returns status 400.
Show answer
Either add @MockitoBean OrderService orderService to the test class, or add @Import(OrderService.class) so the real service is loaded (this may in turn need the service's own dependencies). For a test that only checks a 400 response for an invalid body, use @MockitoBean. Validation happens in the web layer before the service is called, so the real service logic adds nothing and would pull in more dependencies.
Exercise
Your @SpringBootApplication class also carries @EnableScheduling and a @Bean method that creates a client connecting to an external system. Your @WebMvcTest tests are slow and sometimes fail with connection errors. Why, and what is the fix?
Show answer
Slice tests still process the configuration on the @SpringBootApplication class, so the scheduler starts and the client bean is created in every slice. Move @EnableScheduling and the @Bean method into separate @Configuration classes, which the web slice does not scan by default, so the web test no longer loads them.