Contrast the full context @SpringBootTest builds via configuration detection with a sliced test like @WebMvcTest. When does detection still apply?
answer
- Detection = which root; scope = how much loaded
- Slices reuse the SAME @SpringBootConfiguration search
- @WebMvcTest keeps controllers, drops services (mock them)
- @SpringBootTest = full scan + full auto-config
- webEnvironment picks MOCK vs real port
basics
~20 s@SpringBootTest loads the full application context (all your beans + auto-configuration) by discovering the @SpringBootConfiguration class. A slice like @WebMvcTest loads only a narrow layer. Both still find the main class the same way to know where to start.
solid answer
~40 s@SpringBootTest discovers your `@SpringBootConfiguration` (the `@SpringBootApplication` class) and builds the *full* context: component scanning of all your packages plus full auto-configuration — the closest thing to production. Slice annotations (`@WebMvcTest`, `@DataJpaTest`, `@JsonTest`, `@WebFluxTest`, `@RestClientTest`) use the *same* upward package-tree search to locate the `@SpringBootConfiguration` class, but then they **filter** the context: only a curated set of auto-configurations and bean types for that layer are loaded (e.g. `@WebMvcTest` keeps `@Controller`, `@ControllerAdvice`, filters, `MockMvc`, but drops `@Service`/`@Repository`). So configuration *detection* is shared; what differs is the *scope* of what's instantiated. Practical implication: slices are faster and more isolated (you mock collaborators), full `@SpringBootTest` is heavier but exercises real wiring. Both can be narrowed further with an explicit config on the slice via its own attributes.
code
java · 17 lines// FULL context: discovers com.myapp.Application, loads everything
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class OrderEndToEndTest {
@Autowired TestRestTemplate rest; // real server, real service+repo beans
}
// SLICE: same package-tree search anchors it, but only the web layer loads
@WebMvcTest(OrderController.class)
class OrderControllerWebTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orderService; // service excluded -> must mock
@Test void returns200() throws Exception {
given(orderService.find(1L)).willReturn(new Order(1L));
mvc.perform(get("/orders/1")).andExpect(status().isOk());
}
}go deeper
Know @SpringBootTest = whole app, a slice = one layer.
Name specific slices and what each loads/excludes; know you mock collaborators in slices.
Separate detection (shared) from scope (differs); reason about fidelity vs speed and the context cache.
Define a testing strategy balancing full vs slice tests and guard context-cache efficiency across a large suite.
### Two axes: where config is *found* vs how much is *loaded* Configuration **detection** answers "which class is the root of the configuration?" Context **scope** answers "given that root, which beans get instantiated?" `@SpringBootTest` and the slices share the first and differ on the second. ### Full context: @SpringBootTest - Discovers `@SpringBootConfiguration` by searching up the package tree (as covered elsewhere). - Because that class is `@SpringBootApplication`, you get `@ComponentScan` over your packages **and** full `@EnableAutoConfiguration`. - Result: every `@Component`/`@Service`/`@Repository`/`@Controller`, plus auto-configured infrastructure (JPA, security, Jackson, web) — a near-production `ApplicationContext`. - `webEnvironment` controls the server: `MOCK` (default, no real port, `MockMvc`), `RANDOM_PORT`/`DEFINED_PORT` (real embedded server + `TestRestTemplate`/`WebTestClient`), `NONE`. ### Sliced context: the @…Test family - `@WebMvcTest`, `@DataJpaTest`, `@JsonTest`, `@WebFluxTest`, `@RestClientTest`, `@JdbcTest`, etc. - They **also** perform the same `@SpringBootConfiguration` upward search to anchor the context — so the root-package convention matters for slices too. - But they replace blanket auto-configuration with a **curated** list relevant to one layer and apply a **type filter** (`TypeExcludeFilter`) so only beans of that layer are created: - `@WebMvcTest`: MVC infrastructure, `@Controller`, `@ControllerAdvice`, `Converter`, `Filter`, `MockMvc`; **excludes** `@Component`/`@Service`/`@Repository`. Collaborators are supplied via `@MockBean`/`@MockitoBean`. - `@DataJpaTest`: JPA `@Entity`, repositories, `TestEntityManager`, an embedded/replaced DB, transaction-per-test rollback; excludes web/service beans. - You can scope a slice to one controller: `@WebMvcTest(OrderController.class)`. ### Why detection still applies to slices Slices need a configuration anchor to know your base package for their (filtered) scanning and to honor test-relevant beans. They reuse `SpringBootTestContextBootstrapper`'s finder; if no `@SpringBootConfiguration` is reachable, a slice fails with the same "Unable to find a @SpringBootConfiguration" error. Override with the slice's own mechanisms or `@ContextConfiguration`. ### Trade-offs - **Full `@SpringBootTest`:** highest fidelity, catches wiring/auto-config issues, slowest, heaviest context (watch the context cache — distinct configs create distinct cached contexts). - **Slices:** fast, focused, force you to mock collaborators (better unit-of-layer isolation), but don't prove end-to-end wiring. ### Gotchas - Mixing a slice with `@SpringBootTest`-style expectations (autowiring a `@Service` in a `@WebMvcTest`) fails because the bean was filtered out — you must `@MockBean` it. - Adding `@SpringBootTest` **and** a slice annotation together is contradictory and misconfigures the context. - Overusing many bespoke `classes`/slice combos fragments the **context cache**, slowing the whole suite.
- Do slice tests like @WebMvcTest use the same @SpringBootConfiguration detection?Yes. Slices anchor on the same upward package-tree search for @SpringBootConfiguration to establish the base package and pick up test-relevant beans; they then apply auto-config filtering and a TypeExcludeFilter to load only that layer. Missing a reachable @SpringBootConfiguration fails a slice with the same error.
- Why does autowiring a @Service inside a @WebMvcTest fail, and how do you fix it?@WebMvcTest's type filter excludes @Service/@Repository beans, so the service isn't in the context and injection fails with NoSuchBeanDefinitionException. Fix by declaring it as a mock with @MockBean/@MockitoBean (or switch to full @SpringBootTest if you truly need the real collaborator).
- How can too many distinct configurations hurt test suite performance?Spring caches contexts keyed by their configuration. Each unique classes list, property set, or slice combination creates a separate cached context and a fresh container startup. Proliferating bespoke configs defeats caching, so the suite pays repeated context-startup cost — standardize on a few shared setups.
saying these in an interview costs you the question
- Saying slices don't need any @SpringBootConfiguration (they use the same finder)
- Claiming @WebMvcTest loads the full context just filtered by URL
- Expecting @Service beans to autowire in a @WebMvcTest without mocking
- Combining @SpringBootTest and a slice annotation on the same class