@WebMvcTest وMockMvc
في هذا الدرس 4 موضوعات
هذا الدرس مخطط له. يعرض المخطط أدناه الموضوعات التي سيغطيها، ولم يُنشر الدرس الكامل بعد.
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
في هذا الدرس
test a controller through HTTP without starting a server.
الموضوعات المخطط لها
@WebMvcTest(ProductController.class)loads only the web layer (controller, advice, JSON), not services or repositories.- Provide the service as a mock bean (
@MockitoBeanin recent Spring,@MockBeanin older; verify version before recording). MockMvcsends fake requests and checks status, JSON, and headers.- Test success, validation failure (400), and not found (404), and check the body, not only the status.
تفاصيل المخطط المبدئي
عرض عملي
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mvc;
@MockitoBean ProductService service;
@Test void notFound() throws Exception {
when(service.get(9)).thenThrow(new NotFoundException("Product", 9));
mvc.perform(get("/products/9"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.detail").value("Product 9 not found"));
}
}اختبر فهمك
What does @WebMvcTest not load?
أظهر الإجابة
Services, repositories, and the rest of the app.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.