0Pricing
Spring Boot 4 Microservices & REST APIs · Lekcja

Testy warstwy Web z MockMvc

Testuj kontrolery za pomocą @WebMvcTest

Testy warstwy Web z MockMvc to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Testing the Web Layer

Web layer tests verify your controllers — request mapping, validation, serialization, and status codes — without starting a full server.

Spring Boot provides @WebMvcTest and MockMvc for this.

@WebMvcTest

@WebMvcTest loads only the web slice: controllers, filters, and converters. Services and repositories are not loaded — you mock them.

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    UserService userService;
}

MockMvc.perform

MockMvc simulates HTTP requests against your controller without a network.

mockMvc.perform(get("/users/1"))
    .andExpect(status().isOk());

Mocking the Service

Use @MockBean to replace the service in the context, then stub it with Mockito.

@Test
void returnsUser() throws Exception {
    when(userService.getById("1"))
        .thenReturn(new User("1", "Alice"));

    mockMvc.perform(get("/users/1"))
        .andExpect(status().isOk());
}

Asserting JSON with jsonPath

jsonPath verifies fields in the JSON response body.

mockMvc.perform(get("/users/1"))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.name").value("Alice"))
    .andExpect(jsonPath("$.id").value("1"));

Testing POST Requests

Send a JSON body with content and contentType.

mockMvc.perform(post("/users")
    .contentType(MediaType.APPLICATION_JSON)
    .content("{\"name\":\"Bob\"}"))
    .andExpect(status().isCreated());

Asserting Error Statuses

Verify 404 or 400 responses for missing resources or invalid input.

when(userService.getById("99"))
    .thenThrow(new NotFoundException());

mockMvc.perform(get("/users/99"))
    .andExpect(status().isNotFound());

Testing Validation

When a request fails bean validation, expect a 400 Bad Request.

mockMvc.perform(post("/users")
    .contentType(MediaType.APPLICATION_JSON)
    .content("{\"name\":\"\"}"))
    .andExpect(status().isBadRequest());

Checking Headers

Assert response headers such as Location after a create.

mockMvc.perform(post("/users")
    .contentType(MediaType.APPLICATION_JSON)
    .content("{\"name\":\"Bob\"}"))
    .andExpect(header().string("Location",
        "/users/2"));

Query Parameters

Add request parameters with param.

mockMvc.perform(get("/users")
    .param("name", "Alice"))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.length()").value(1));

Printing the Result

Use andDo(print()) to log the full request and response while debugging.

mockMvc.perform(get("/users/1"))
    .andDo(print())
    .andExpect(status().isOk());

Quick Check

Test your understanding of MockMvc.

Recap

You learned to test controllers in isolation:

  • @WebMvcTest loads only the web slice
  • MockMvc.perform simulates requests
  • @MockBean replaces services
  • jsonPath, status(), header() for assertions

Często zadawane pytania

Czy lekcja „Testy warstwy Web z MockMvc” jest bezpłatna?

Tak — pełny tekst „Testy warstwy Web z MockMvc” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Co nauczysz się w „Testy warstwy Web z MockMvc”?

Testuj kontrolery za pomocą @WebMvcTest Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?

Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Testy warstwy Web z MockMvc”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?

Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Testy jednostkowe z JUnit i Mockito
  2. Testy warstwy Web z MockMvc
  3. Testy integracyjne z @SpringBootTest
  4. Rzeczywiste zależności z Testcontainers
← Powrót do Spring Boot 4 Microservices & REST APIs