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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Slice tests load only the web layer, keeping controller tests fast and focused on request/response behavior.
- 2Mocking collaborators lets you drive every HTTP branch — success, not-found, conflict — without a real service or database.
- 3Verifying interactions proves not just the response but that the controller called (or skipped) the right dependencies.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/slicing-the-web-layer-with-webmvctest-in-spring-explained-java-fb85/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.