@WebMvcTest creates a focused Spring MVC test context instead of loading the whole application with @SpringBootTest. It includes web components such as @Controller and @ControllerAdvice and configures MockMvcTester. Business and data layers are not part of the slice. section 5.1 section 5.8
Test a controller error response
Add spring-boot-starter-webmvc-test as a test-scoped dependency. A focused test can use @WebMvcTest(controllers = CityController.class), replace the controller’s CityService dependency with @MockitoBean, and inject MockMvcTester. Configure the mock to throw CityAlreadySelectedException when a city is added; then POST JSON to /api/city and assert HTTP 409 CONFLICT. This checks the controller and its @ControllerAdvice without loading the service implementation. section 5.3 section 5.8
The annotation’s bootstrapper sets up a mock web test environment. Its type filter normally selects web components; the controllers parameter narrows selection to specified controllers, while includeFilters and excludeFilters customize it. Web MVC and MockMvc auto-configuration provide the testing infrastructure. section 5.7 section 5.7.2
Listing 5.18 Simplified code for @WebMvcTest annotation
@ExtendWith(SpringExtension.class) #1
@BootstrapWith(WebMvcTestContextBootstrapper.class) #2
@TypeExcludeFilters(WebMvcTypeExcludeFilter.class) #3
@OverrideAutoConfiguration(enabled = false) #4
@ImportAutoConfiguration #4
@AutoConfigureWebMvc #4
@AutoConfigureMockMvc #4
public @interface WebMvcTest {
String[] properties() default {}; #5
Class<?>[] controllers() default {}; #6
Filter[] includeFilters() default {}; #7
Filter[] excludeFilters() default {}; #7
}
The simplified annotation shows the bootstrapper, type-exclusion filter, web auto-configuration, and selection parameters together. section 5.7
Use the slice when a web edge case needs focused coverage, especially as a full application grows costly to test. A small application may remain clearer with @SpringBootTest. Choose slices deliberately: many distinct contexts can cause context thrashing, and a test class cannot combine multiple slice annotations. section 5.3 section 5.7 section 5.8
