Video tayyorlanmoqda

Strong Middle 🧪 Testlash

Validatsiya va biznes xatolari uchun API qaytaradigan xato formatini (ProblemDetail) testda qanday kafolatlaysiz?

@WebMvcTest va MockMvc bilan har bir xato turi uchun status kod, application/problem+json content type va javob tanasidagi maydonlarni tekshiraman. Ayniqsa kutilmagan exception 500 qaytarib, ichida stack trace yoki SQL matnini oshkor qilmasligini alohida test qilaman.

📖 Javob

Spring 6'dan ProblemDetail (RFC 9457, avvalgi RFC 7807) standart format sifatida bor. Lekin hamma xato bir xil ko'rinishda chiqishi uchun @ControllerAdvice to'g'ri yozilgan va hamma exception unga yetib kelishi kerak. Front-end va mobil ilova shu maydonlarga tayanadi, shuning uchun bu ham kontrakt.

@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 — standart maydon emas, uni ProblemDetail.setProperty("errors", ...) bilan o'zingiz qo'shasiz; test aynan shu kelishuvni qotiradi.

Nimalarni ro'yxatga olaman: @Valid @RequestBody xatosi (MethodArgumentNotValidException), noto'g'ri JSON (HttpMessageNotReadableException), noto'g'ri path parametri turi, 404 biznes holat, va "boshqa hamma narsa" — 500. Oxirgisi uchun log'ga to'liq xato yoziladi, javobga esa faqat umumiy matn va trace ID.

Advice'ni @Import qilish shart emas — @WebMvcTest @ControllerAdvice'ni o'zi yuklaydi. Lekin aniq yozib qo'ysangiz, test qaysi handler'ni tekshirayotgani ko'rinib turadi.