Testare i livelli web con @WebMvcTest e MockMvc
Esegua slice test sui controller Spring Boot in isolamento usando @WebMvcTest e MockMvc, senza avviare l'intero contesto applicativo.
Testare i livelli web con @WebMvcTest e MockMvc è una lezione Testing Mastery: JUnit, Mockito & Integration Tests 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 Testing Mastery: JUnit, Mockito & Integration Tests, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Testing Mastery: JUnit, Mockito & Integration Tests include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Slice Tests?
Loading the entire Spring context for every controller test is slow. Spring Boot offers test slices that load only the beans you need. @WebMvcTest loads just the web layer.
What @WebMvcTest Loads
@WebMvcTest configures controllers, filters, and JSON converters, but not services or repositories. Those collaborators are supplied as mocks.
Declaring the Test
Target a single controller so the slice stays small and fast.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
}Mocking the Service
The controller's service dependency is replaced with a Mockito mock using @MockBean, which places the mock in the context.
@MockBean
UserService userService;Performing a Request
MockMvc simulates HTTP requests against your controller without a running server.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Stubbing Then Asserting
Stub the mocked service, fire the request, and assert on the response body and status.
when(userService.find(1L))
.thenReturn(new User(1L, "Ada"));
mockMvc.perform(get("/users/1"))
.andExpect(jsonPath("$.name").value("Ada"));Checking Status Codes
Validate error mappings, such as a 404 when the service signals a missing entity.
when(userService.find(9L))
.thenThrow(new NotFoundException());
mockMvc.perform(get("/users/9"))
.andExpect(status().isNotFound());Testing POST with a Body
Send JSON content and verify the controller deserializes and responds correctly.
mockMvc.perform(post("/users")
.contentType("application/json")
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());JsonPath Assertions
jsonPath expressions let you assert on nested fields, array sizes, and values inside the JSON response.
.andExpect(jsonPath("$.items.length()").value(3))Slice vs Full Context
Use @WebMvcTest for focused, fast web-layer tests. Reserve @SpringBootTest for true end-to-end flows where you want the whole context wired.
Speed Benefits
Because only the web layer loads, these tests start in a fraction of the time of a full-context test, encouraging more thorough controller coverage.
Quick Check
How are service dependencies handled in a @WebMvcTest?
Recap
You learned web-layer slice testing:
@WebMvcTestloads only controllers and web infrastructureMockMvcsimulates HTTP requests without a server@MockBeansupplies mocked services- Assert status and body with
jsonPath
Domande Frequenti
La lezione «Testare i livelli web con @WebMvcTest e MockMvc» è gratuita?
Sì — il testo completo di «Testare i livelli web con @WebMvcTest e 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 Testing Mastery: JUnit, Mockito & Integration Tests, passa a CoddyKit PRO. Il corso Testing Mastery: JUnit, Mockito & Integration Tests include 4 lezioni in totale.
Cosa imparerò in «Testare i livelli web con @WebMvcTest e MockMvc»?
Esegua slice test sui controller Spring Boot in isolamento usando @WebMvcTest e MockMvc, senza avviare l'intero contesto applicativo. Eserciti Testing Mastery: JUnit, Mockito & Integration Tests 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 Testing Mastery: JUnit, Mockito & Integration Tests?
Non è richiesta alcuna esperienza precedente. Testing Mastery: JUnit, Mockito & Integration Tests 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 livelli web con @WebMvcTest e 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 Testing Mastery: JUnit, Mockito & Integration Tests?
Sì. Ogni lezione Testing Mastery: JUnit, Mockito & Integration Tests 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
- Framework del contesto di test di Spring
- Testare le API RESTful
- Database incorporati per i test
- Testare i livelli web con @WebMvcTest e MockMvc