0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

Testes da camada web com MockMvc

Teste controladores com @WebMvcTest.

Testes da camada web com MockMvc é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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

Perguntas Frequentes

A aula “Testes da camada web com MockMvc” é grátis?

Sim — o texto completo de “Testes da camada web com MockMvc” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “Testes da camada web com MockMvc”?

Teste controladores com @WebMvcTest. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Testes da camada web com MockMvc”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Testes unitários com JUnit e Mockito
  2. Testes da camada web com MockMvc
  3. Testes de integração com @SpringBootTest
  4. Dependências reais com Testcontainers
← Voltar para Spring Boot 4 Microservices & REST APIs