Testing Mastery: JUnit, Mockito & Integration Tests · Aula

Testando camadas web com @WebMvcTest e MockMvc

Teste controladores do Spring Boot isoladamente, por fatias, usando @WebMvcTest e MockMvc sem iniciar todo o contexto da aplicação.

Aula 4 de 413 etapas

Testando camadas web com @WebMvcTest e MockMvc é uma aula grátis de Testing Mastery: JUnit, Mockito & Integration Tests no CoddyKit. Esta é a aula 4 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 Testing Mastery: JUnit, Mockito & Integration Tests, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Testing Mastery: JUnit, Mockito & Integration Tests inclui 4 aulas no total.

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

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:

  • @WebMvcTest loads only controllers and web infrastructure
  • MockMvc simulates HTTP requests without a server
  • @MockBean supplies mocked services
  • Assert status and body with jsonPath
Grátis para começar

Aprenda Testing Mastery: JUnit, Mockito & Integration Tests com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Testando camadas web com @WebMvcTest e MockMvc” é grátis?

Sim — o texto completo de “Testando camadas web com @WebMvcTest e 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 Testing Mastery: JUnit, Mockito & Integration Tests, atualize para CoddyKit PRO. O curso de Testing Mastery: JUnit, Mockito & Integration Tests inclui 4 aulas no total.

O que vou aprender em “Testando camadas web com @WebMvcTest e MockMvc”?

Teste controladores do Spring Boot isoladamente, por fatias, usando @WebMvcTest e MockMvc sem iniciar todo o contexto da aplicação. Você pratica Testing Mastery: JUnit, Mockito & Integration Tests 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 Testing Mastery: JUnit, Mockito & Integration Tests?

Nenhuma experiência prévia é necessária. Testing Mastery: JUnit, Mockito & Integration Tests 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 4 de 4.

Quanto tempo leva a aula “Testando camadas web com @WebMvcTest e 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 Testing Mastery: JUnit, Mockito & Integration Tests?

Sim. Cada aula de Testing Mastery: JUnit, Mockito & Integration Tests 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. Estrutura de Contexto de Testes do Spring
  2. Testando APIs RESTful
  3. Bancos de Dados Incorporados para Testes
  4. Testando camadas web com @WebMvcTest e MockMvc
← Voltar para Testing Mastery: JUnit, Mockito & Integration Tests