skip to content

Your @WebMvcTest needs an auto-configuration the slice doesn't include (say Spring Security's or a custom one). How do you add it without switching to @SpringBootTest?

level: seniorimportance: should knowfreq 55%

answer

  1. @ImportAutoConfiguration(X.class) = add one auto-config
  2. @AutoConfigureXxx = prebuilt enabler
  3. @Import ≠ @ImportAutoConfiguration (ordering/conditions)
  4. @TestConfiguration nested = extra beans
  5. don't fall back to @SpringBootTest for one bean

basics

~10 s

Add the specific auto-configuration back onto the slice. Use the relevant @AutoConfigureXxx annotation (e.g. one exists automatically), or @ImportAutoConfiguration(TheAutoConfiguration.class) to pull in exactly the auto-config classes you need — no full context required.

solid answer

~40 s

Because a slice sets auto-configuration default-off and opts specific classes back in, extending it means opting one more in. Two tools: (1) `@AutoConfigureXxx` — the pre-built enablers Boot ships (e.g. `@AutoConfigureMockMvc`, `@AutoConfigureJsonTesters`); some layers already stack these. (2) `@ImportAutoConfiguration(SomeAutoConfiguration.class)` — the general-purpose escape hatch to import any specific auto-configuration class (yours or a framework's) onto the test, in isolation, respecting its ordering. For Spring Security in a web slice, the security auto-config is generally already applied by `@WebMvcTest`; if you need something extra you add `@ImportAutoConfiguration`. You can also just declare an `@TestConfiguration` inner class or `@Import` a plain `@Configuration` to add beans. Prefer these targeted additions over widening to `@SpringBootTest`, which would defeat the slice's speed and isolation.

code

java · 21 lines
java
@WebMvcTest(OrderController.class)
// Pull in a specific auto-configuration onto the slice — honoring its
// @ConditionalOnXxx / @AutoConfigureAfter ordering, unlike plain @Import
@ImportAutoConfiguration(CustomMetricsAutoConfiguration.class)
class OrderControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService orderService;

    // Need a couple of extra beans (not a whole auto-config)? Add them additively:
    @TestConfiguration
    static class Fixtures {
        @Bean Clock clock() { return Clock.fixed(Instant.EPOCH, ZoneOffset.UTC); }
    }

    @Test
    void placesOrder() throws Exception {
        mvc.perform(post("/orders").with(csrf()))
           .andExpect(status().isCreated());
    }
}

go deeper

for a junior

Know that you can add missing pieces without @SpringBootTest, e.g. a nested @TestConfiguration.

for a middle

Use @ImportAutoConfiguration and existing @AutoConfigureXxx annotations to extend a slice.

for a senior

Explain @Import vs @ImportAutoConfiguration, prerequisite-ordering pitfalls, and @AutoConfigureTestDatabase(replace=NONE).

for a principal

Decide policy: when extension is legitimate vs when the test should be a full integration test; manage custom-starter auto-config imports.

## The situation Slices are deliberately minimal — auto-configuration is default-off (`@OverrideAutoConfiguration(enabled=false)`), and only a curated set is re-enabled. So the common problem is: *'the slice doesn't wire up the thing I need.'* You have several targeted ways to add it back **without** falling back to a full `@SpringBootTest`. ## Option 1 — `@ImportAutoConfiguration` (the precise tool) `@ImportAutoConfiguration` imports **specific auto-configuration classes** into the test context, applying their conditions and ordering exactly as Boot would, but only for the classes you name: ```java @WebMvcTest(OrderController.class) @ImportAutoConfiguration(CustomMetricsAutoConfiguration.class) class OrderControllerTest { ... } ``` This is different from `@Import`: `@Import` just registers a config class as-is, while `@ImportAutoConfiguration` treats it as *auto-configuration* — honoring `@AutoConfigureBefore/After`, `@ConditionalOnXxx`, etc. Use it for framework or your own `@AutoConfiguration`-annotated classes. ## Option 2 — a purpose-built `@AutoConfigureXxx` Boot ships many `@AutoConfigureXxx` meta-annotations (`@AutoConfigureMockMvc`, `@AutoConfigureWebClient`, `@AutoConfigureJsonTesters`, `@AutoConfigureTestDatabase`, `@AutoConfigureRestDocs`, `@AutoConfigureWireMock`, etc.). Each is itself `@ImportAutoConfiguration`-backed. If one exists for what you need, slap it on the test class. Some are already stacked inside the slice (e.g. `@WebMvcTest` includes `@AutoConfigureMockMvc`, `@AutoConfigureWebMvc`, security, cache, JSON testers). ## Option 3 — add beans directly If you just need a few beans (not full auto-config), declare a static nested `@TestConfiguration` class (picked up automatically when nested) or `@Import` a plain `@Configuration`: ```java @WebMvcTest(OrderController.class) class OrderControllerTest { @TestConfiguration static class ExtraBeans { @Bean Clock fixedClock() { return Clock.fixed(...); } } } ``` (`@TestConfiguration` is *additive* and, when a nested static class, is registered on top of the slice; a top-level `@Configuration` referenced via `@Import` works too.) ## Option 4 — property to enable more Some behaviors are gated behind `@AutoConfigureXxx` attributes or properties (e.g. `@AutoConfigureTestDatabase(replace = Replace.NONE)` to use the real DB instead of embedded). ## What NOT to do - Don't jump to `@SpringBootTest` for one missing bean — you lose speed and layer isolation. - Don't `@ComponentScan` broadly to 'find' the bean — that re-imports the world and undermines the slice. - Don't confuse `@Import` (register any config) with `@ImportAutoConfiguration` (register auto-config with ordering/conditions). ## Gotchas - Order matters: importing an auto-config that itself has `@ConditionalOnBean`/`@AutoConfigureAfter` dependencies may still not activate if its prerequisites aren't present in the slim slice — you may need to import those too. - A custom starter's auto-config must be listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` for `@ImportAutoConfiguration` value-less usage; naming the class explicitly avoids that. - Security: `@WebMvcTest` already applies Spring Security auto-config, so filter-chain tests work; you supply user context via `@WithMockUser` / `SecurityMockMvcRequestPostProcessors`.

  • What's the difference between @Import and @ImportAutoConfiguration?
    @Import registers a configuration class verbatim. @ImportAutoConfiguration registers it as auto-configuration, applying @AutoConfigureBefore/After ordering and @ConditionalOnXxx evaluation, and (value-less) can source the list from AutoConfiguration.imports. Use the latter for auto-config classes.
  • How do you make @DataJpaTest run against your real database instead of an embedded one?
    Annotate with @AutoConfigureTestDatabase(replace = Replace.NONE). By default the slice swaps the DataSource for an embedded DB; NONE keeps the configured one.
  • You import an auto-config but its beans still don't appear — why?
    Its @ConditionalOnBean/@AutoConfigureAfter prerequisites may be missing in the slim slice. You must also import those prerequisite auto-configs (or the beans they need) so its conditions match.

saying these in an interview costs you the question

  • Reaching for @SpringBootTest whenever a slice lacks a bean
  • Using @Import for an auto-config class and expecting ordering/conditions to be honored
  • Broadening @ComponentScan to 'find' missing beans, re-loading the whole app

context