A test slice is a Spring Boot test annotation that loads a restricted application context for one technical area, rather than the full context loaded by @SpringBootTest. It selects relevant application beans and supplies the testing infrastructure for that area. Use a slice when a large or slow-starting application makes full-context tests too costly for frequent feedback. section 5.0 section 5.2
Choose the slice that matches the boundary under test:
- @WebMvcTest loads web components such as controllers and controller advice, and configures MockMvcTester. Supply replacements, such as @MockitoBean or @TestBean, for dependencies from excluded layers. section 5.1 section 5.8
- @RestClientTest loads explicitly named components with HTTP-client testing infrastructure. It connects a RestClient built through Spring’s builder to a configurable MockRestServiceServer; other service dependencies still need test beans or mocks. section 5.4
- @DataJpaTest restricts scanning to entities and repositories, adds data-related configuration, replaces the database with an in-memory instance, and makes tests transactional. Ordinary business services have no dedicated technical slice. section 5.1
Test a controller’s error response
Annotate a test with @WebMvcTest(controllers = { CityController.class }). Provide its CityService dependency with @MockitoBean, configure that mock to throw CityAlreadySelectedException, then use the injected MockMvcTester to POST a city ID and assert HTTP 409 Conflict. The test exercises the web error handling without loading the business or persistence layers. section 5.3
Slices are not free: each still starts a Spring context. Many distinct contexts can exhaust the default cache of 32 contexts and cause repeated startup. Prefer a small, reusable set of test contexts when slicing would fragment a suite; a full-context test can be simpler for a small application. For business-domain rather than technical boundaries, Spring Modulith offers @ApplicationModuleTest and @ModuleSlicing. section 5.2 section 5.8
Under the annotation, a slice uses a test-context bootstrapper, type-exclusion filters to select classes, and targeted auto-configuration. Because a test class can have only one bootstrapper, do not combine slice annotations on the same class. section 5.7
