Video in progress

Strong Middle 🧪 Testing

How do you guarantee, in a test, the error format the API returns (ProblemDetail) for validation and business errors?

With @WebMvcTest and MockMvc, for each kind of error I check the status code, the application/problem+json content type and the fields in the response body. I specifically test that an unexpected exception returns 500 without exposing a stack trace or SQL text.

📖 Answer

Since Spring 6 there's ProblemDetail (RFC 9457, formerly RFC 7807) as a standard format. But for every error to come out in the same shape, the @ControllerAdvice has to be written correctly and every exception has to reach it. The front end and the mobile app rely on these fields, so this is a contract too.

@WebMvcTest(OrderController.class)
@Import(ApiExceptionHandler.class)
class OrderErrorFormatTest {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService orders;

    @Test
    @WithMockUser
    void validationErrorListsFields() throws Exception {
        mvc.perform(post("/api/orders").with(csrf())
                .contentType(APPLICATION_JSON).content("{\"courseId\":null}"))
           .andExpect(status().isBadRequest())
           .andExpect(content().contentType(APPLICATION_PROBLEM_JSON))
           .andExpect(jsonPath("$.title").value("Validation failed"))
           .andExpect(jsonPath("$.errors[0].field").value("courseId"));
    }

    @Test
    @WithMockUser
    void unexpectedErrorDoesNotLeakInternals() throws Exception {
        when(orders.create(any())).thenThrow(new DataIntegrityViolationException("duplicate key orders_pkey"));
        mvc.perform(post("/api/orders").with(csrf())
                .contentType(APPLICATION_JSON).content("{\"courseId\":7}"))
           .andExpect(status().isConflict())
           .andExpect(jsonPath("$.detail").value(not(containsString("orders_pkey"))));
    }
}

errors isn't a standard field; you add it yourself with ProblemDetail.setProperty("errors", ...), and the test pins down exactly that agreement.

What I put on the list: a @Valid @RequestBody failure (MethodArgumentNotValidException), invalid JSON (HttpMessageNotReadableException), a wrong path parameter type, a 404 business case, and "everything else", which is a 500. For the last one the full error goes to the log, while the response gets only a generic message and a trace ID.

You don't have to @Import the advice, since @WebMvcTest loads @ControllerAdvice on its own. But if you write it explicitly, it's clear which handler the test is checking.