java 47 lines · 9 steps

Slicing the web layer with @WebMvcTest in Spring

How @WebMvcTest boots just the controller layer and drives it with MockMvc against mocked collaborators.

Explained by highlit
1@WebMvcTest(OrderController.class)
2class OrderControllerTest {
3 
4 @Autowired
5 private MockMvc mockMvc;
6 
7 @MockBean
8 private OrderService orderService;
9 
10 @MockBean
11 private InventoryClient inventoryClient;
12 
13 @Test
14 void returnsOrderWhenFound() throws Exception {
15 var order = new OrderResponse(42L, "SHIPPED", new BigDecimal("129.99"));
16 given(orderService.findById(42L)).willReturn(Optional.of(order));
17 
18 mockMvc.perform(get("/api/orders/{id}", 42L).accept(MediaType.APPLICATION_JSON))
19 .andExpect(status().isOk())
20 .andExpect(jsonPath("$.id").value(42))
21 .andExpect(jsonPath("$.status").value("SHIPPED"))
22 .andExpect(jsonPath("$.total").value(129.99));
23 
24 verify(orderService).findById(42L);
25 }
26 
27 @Test
28 void returns404WhenMissing() throws Exception {
29 given(orderService.findById(anyLong())).willReturn(Optional.empty());
30 
31 mockMvc.perform(get("/api/orders/{id}", 7L))
32 .andExpect(status().isNotFound());
33 }
34 
35 @Test
36 void rejectsPlacementWhenOutOfStock() throws Exception {
37 given(inventoryClient.isAvailable("SKU-100", 3)).willReturn(false);
38 
39 mockMvc.perform(post("/api/orders")
40 .contentType(MediaType.APPLICATION_JSON)
41 .content("{\"sku\":\"SKU-100\",\"quantity\":3}"))
42 .andExpect(status().isConflict())
43 .andExpect(jsonPath("$.error").value("OUT_OF_STOCK"));
44 
45 verifyNoInteractions(orderService);
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Slice tests load only the web layer, keeping controller tests fast and focused on request/response behavior.
  2. 2Mocking collaborators lets you drive every HTTP branch — success, not-found, conflict — without a real service or database.
  3. 3Verifying interactions proves not just the response but that the controller called (or skipped) the right dependencies.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Slicing the web layer with @WebMvcTest in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code