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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 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.