Video tayyorlanmoqda

Middle 🧪 Testlash

REST controller'ni @WebMvcTest va MockMvc yordamida qanday test qilasiz?

@WebMvcTest(Controller.class) faqat shu controller'ni yuklaydi, servis bog'liqliklari mock qilinadi. MockMvc orqali haqiqiy HTTP so'rov kabi so'rov yuborib, status, header va JSON tanasini tekshirasiz — server port ochilmaydi.

📖 Javob

@WebMvcTest(ProductController.class)
class ProductControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean ProductService service;   // Boot 3.4 dan oldin: @MockBean

    @Test
    void mahsulot_topilsa_200_qaytadi() throws Exception {
        when(service.find(7L)).thenReturn(new ProductDto(7L, "Choynak", 85_000));

        mvc.perform(get("/api/products/7"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.name").value("Choynak"))
           .andExpect(jsonPath("$.price").value(85000));
    }

    @Test
    void bosh_nom_bilan_yaratish_400() throws Exception {
        mvc.perform(post("/api/products")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"name": "", "price": 1000}
                    """))
           .andExpect(status().isBadRequest());

        verifyNoInteractions(service);
    }
}

Bu test nimani tekshiradi: URL mapping, @Valid ishlashi, @ControllerAdvice'dagi xato formati, Jackson serializatsiyasi. Biznes mantiqni esa tekshirmaydi — u servis testida.

Spring Security loyihada bo'lsa, @WebMvcTest uni ham yuklaydi va so'rovlar 401 qaytaradi. Shuning uchun @WithMockUser yoki .with(jwt()) kerak bo'ladi.

Spring 6.2'dan MockMvcTester paydo bo'ldi — AssertJ uslubida yozish uchun. Yangi loyihalarda ko'rib chiqishga arziydi.