Video in progress
What's the difference between @SpringBootTest and @WebMvcTest?
@SpringBootTest starts the whole application — for integration tests. @WebMvcTest loads only the web layer (controllers, advice, filters, Jackson), and services are mocked — fast and focused.
📖 Answer
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orders; // Boot 3.4+; before that @MockBean
@Test
void returns404WhenMissing() throws Exception {
given(orders.find(7L)).willReturn(Optional.empty());
mvc.perform(get("/api/orders/7"))
.andExpect(status().isNotFound());
}
}
@SpringBootTest(webEnvironment = RANDOM_PORT)
@Testcontainers
class CheckoutFlowTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");
@Autowired TestRestTemplate http;
// full flow against a real database
}
When to use which:
- JSON format, status codes, validation, security rules —
@WebMvcTest; - JPA queries —
@DataJpaTest; - several layers working correctly together —
@SpringBootTest.
A word on speed: tests with the same configuration share one cached context. If every test has a different set of @MockitoBeans, the context gets started over and over.
Sign up to mark studied questions and save your progress.