Video in progress
How do you test a REST controller with @WebMvcTest and MockMvc?
@WebMvcTest(Controller.class) loads only that controller, and the service dependencies are mocked. With MockMvc you send a request as if it were a real HTTP request and check the status, headers and JSON body; no server port is opened.
📖 Answer
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mvc;
@MockitoBean ProductService service; // before Boot 3.4: @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);
}
}
What this test checks: URL mapping, that @Valid works, the error format in @ControllerAdvice, Jackson serialization. It doesn't check business logic; that goes in the service test.
If Spring Security is in the project, @WebMvcTest loads it too and requests return 401. So you'll need @WithMockUser or .with(jwt()).
Since Spring 6.2 there's MockMvcTester for writing in AssertJ style. Worth a look in new projects.
Sign up to mark studied questions and save your progress.