java / intermediate
Snippet
Verifying Custom Controller Advice Responses with MockMvc and JSON Path
Integration slice testing with @WebMvcTest validates that business exceptions thrown from service layers are correctly translated into RFC 7807 problem details or custom error structures by @ExceptionHandler methods.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@WebMvcTest(OrderController.class)class OrderControllerTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate OrderService orderService;@Testvoid shouldReturnNotFoundProblemDetails() throws Exception {Mockito.when(orderService.getOrder(404L)).thenThrow(new EntityNotFoundException("Order 404 not found"));mockMvc.perform(MockMvcRequestBuilders.get("/api/orders/404")).andExpect(MockMvcResultMatchers.status().isNotFound()).andExpect(MockMvcResultMatchers.jsonPath("$.detail").value("Order 404 not found"));}}
spring
Breakdown
1
@WebMvcTest(OrderController.class)
Focuses the test context exclusively on the MVC layer, configuring MockMvc and controller advice.
2
Mockito.when(orderService.getOrder(404L)).thenThrow(new EntityNotFoundException("Order 404 not found"));
Simulates a failure condition in the mocked service layer.
3
.andExpect(MockMvcResultMatchers.jsonPath("$.detail").value("Order 404 not found"));
Uses JSONPath syntax to assert the serialized structure of the error payload.