Testare i controller web con MockMvc
Scriva test mirati per i suoi endpoint REST usando MockMvc per simulare richieste HTTP senza avviare un server reale.
Testare i controller web con MockMvc è una lezione Spring Boot 4 Complete Guide gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Complete Guide, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Complete Guide include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Test Controllers in Isolation?
Controller tests verify routing, request mapping, status codes, and JSON serialization without the cost of a full server. MockMvc makes this fast and precise.
Introducing @WebMvcTest
The @WebMvcTest annotation loads only the web layer, your controllers and their supporting beans, keeping the test slice small and quick.
@WebMvcTest(UserController.class)
class UserControllerTest {
}Injecting MockMvc
Inside a @WebMvcTest, Spring provides an auto-configured MockMvc instance you autowire to perform simulated requests.
@Autowired
MockMvc mockMvc;Performing a GET Request
Use the fluent API to perform a request and chain expectations on the response.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Mocking the Service Layer
Controllers depend on services, so you replace them with mocks using @MockBean. This isolates the controller from real business logic.
@MockBean
UserService userService;Stubbing Behavior
Combine Mockito stubbing with the request to control what the service returns.
when(userService.find(1L)).thenReturn(new User("Ada"));Asserting JSON Content
Use jsonPath to verify specific fields in the response body.
mockMvc.perform(get("/users/1"))
.andExpect(jsonPath("$.name").value("Ada"));Testing POST with a Body
Send a JSON payload and assert the created status, verifying your endpoint accepts and processes input correctly.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());Verifying Validation Errors
Send invalid input and assert a 400 Bad Request to confirm your validation rules actually fire.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest());Verifying Interactions
Use Mockito's verify to confirm the controller actually called the service the expected number of times.
verify(userService).find(1L);When to Use Full Integration Tests
MockMvc slice tests are fast but mock the service. For end-to-end confidence across the real stack, complement them with full @SpringBootTest integration tests.
Quick Check
Test your understanding of MockMvc controller testing.
Recap
You used @WebMvcTest with MockMvc to test endpoints, mocked services with @MockBean, and asserted status codes and JSON. These slice tests are a fast first line of defense.
Domande Frequenti
La lezione «Testare i controller web con MockMvc» è gratuita?
Sì — il testo completo di «Testare i controller web con MockMvc» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Complete Guide, passa a CoddyKit PRO. Il corso Spring Boot 4 Complete Guide include 4 lezioni in totale.
Cosa imparerò in «Testare i controller web con MockMvc»?
Scriva test mirati per i suoi endpoint REST usando MockMvc per simulare richieste HTTP senza avviare un server reale. Eserciti Spring Boot 4 Complete Guide con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Spring Boot 4 Complete Guide?
Non è richiesta alcuna esperienza precedente. Spring Boot 4 Complete Guide su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Testare i controller web con MockMvc»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Complete Guide?
Sì. Ogni lezione Spring Boot 4 Complete Guide include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Test unitari con JUnit e Mockito
- Test di integrazione con Spring Boot
- Slice test e Testcontainers
- Testare i controller web con MockMvc