Video tayyorlanmoqda

Junior 🌱 Spring

MockMvc bilan controller endpoint'ini qanday test qilasiz?

@WebMvcTest faqat web qatlamni ko'taradi, MockMvc esa server ochmasdan HTTP so'rov yuboradi, servis mock bo'ladi. Keyin status, header va JSON tanasini tekshirasiz.

📖 Javob

@WebMvcTest(BookController.class)
class BookControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean BookService service;   // Boot 3.4 gacha: @MockBean

    @Test
    void returnsBook() throws Exception {
        when(service.find(1L)).thenReturn(new BookDto(1L, "O'tkan kunlar"));

        mvc.perform(get("/api/books/1").accept(MediaType.APPLICATION_JSON))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.title").value("O'tkan kunlar"));
    }

    @Test
    void rejectsEmptyTitle() throws Exception {
        mvc.perform(post("/api/books")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"title\":\"\"}"))
           .andExpect(status().isBadRequest());
    }
}

Bu test URL mapping, JSON serializatsiya, validatsiya va @ControllerAdvice'dagi xato javoblarini tekshiradi — hammasi haqiqiy Spring MVC orqali o'tadi, faqat tarmoq yo'q. Servis logikasi va baza esa tekshirilmaydi, ular mock.

Spring Security qo'shilgan bo'lsa, so'rov 401 qaytarishi mumkin — unda @WithMockUser kerak bo'ladi. Spring Framework 6.2 da AssertJ uslubidagi MockMvcTester ham qo'shildi, yangi testlarni u bilan yozsa ham bo'ladi.