Pular para o conteúdo principal

TP9.3 - Testes REST API com MockMvc

Objetivos do TP​

Neste TP, você irá:

  1. ✅ Testar um controller REST completo com MockMvc
  2. ✅ Validar as requisições GET, POST, PUT, DELETE
  3. ✅ Testar as respostas JSON com JSONPath
  4. ✅ Testar erros (404, 400, 500)
  5. ✅ Testar com autenticação

Duração estimada: 1h30


Contexto​

Você tem um ProductController que expõe uma API REST CRUD. Você deve testar todos os endpoints com MockMvc.


Parte 1: O Controller a Ser Testado​

@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductController {

private final ProductService productService;

@GetMapping
public List<Product> getAll() {
return productService.findAll();
}

@GetMapping("/{id}")
public ResponseEntity<Product> getById(@PathVariable Long id) {
return productService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}

@PostMapping
public ResponseEntity<Product> create(@Valid @RequestBody ProductRequest request) {
Product product = productService.create(request);
URI location = URI.create("/api/products/" + product.getId());
return ResponseEntity.created(location).body(product);
}

@PutMapping("/{id}")
public ResponseEntity<Product> update(@PathVariable Long id,
@Valid @RequestBody ProductRequest request) {
return productService.update(id, request)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
if (productService.delete(id)) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
}

@GetMapping("/search")
public List<Product> search(
@RequestParam(required = false) String name,
@RequestParam(required = false) BigDecimal minPrice,
@RequestParam(required = false) BigDecimal maxPrice) {
return productService.search(name, minPrice, maxPrice);
}
}

ProductRequest DTO​

@Data
public class ProductRequest {
@NotBlank(message = "Name is required")
private String name;

private String description;

@NotNull(message = "Price is required")
@Positive(message = "Price must be positive")
private BigDecimal price;

@Min(value = 0, message = "Stock cannot be negative")
private Integer stock;
}

Parte 2: Configuração dos Testes​

@WebMvcTest(ProductController.class)
class ProductControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private ProductService productService;

private Product sampleProduct;

@BeforeEach
void setUp() {
sampleProduct = new Product(1L, "Laptop", "High-end laptop",
new BigDecimal("999.99"), 10, true, null, LocalDateTime.now());
}
}

Parte 3: Testes GET​

Teste 1: GET /api/products​

@Test
@DisplayName("GET /api/products - Deve retornar a lista de produtos")
void getAll_ShouldReturnProducts() throws Exception {
when(productService.findAll()).thenReturn(List.of(sampleProduct));

mockMvc.perform(get("/api/products"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].name").value("Laptop"));
}

Teste 2: GET /api/products/{id} - Sucesso​

@Test
@DisplayName("GET /api/products/{id} - Deve retornar o produto")
void getById_WhenExists_ShouldReturnProduct() throws Exception {
when(productService.findById(1L)).thenReturn(Optional.of(sampleProduct));

mockMvc.perform(get("/api/products/{id}", 1))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("Laptop"))
.andExpect(jsonPath("$.price").value(999.99));
}

Teste 3: GET /api/products/{id} - Not Found​

@Test
@DisplayName("GET /api/products/{id} - Deve retornar 404 se não encontrado")
void getById_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implementar
}

Teste 4: GET /api/products/search​

@Test
@DisplayName("GET /api/products/search - Deve filtrar os produtos")
void search_ShouldFilterProducts() throws Exception {
// TODO: Implementar com params
}

Parte 4: Testes POST​

Teste 5: POST /api/products - Sucesso​

@Test
@DisplayName("POST /api/products - Deve criar um produto")
void create_WithValidData_ShouldReturnCreated() throws Exception {
ProductRequest request = new ProductRequest();
request.setName("New Product");
request.setPrice(new BigDecimal("49.99"));
request.setStock(10);

Product created = new Product(1L, "New Product", null,
new BigDecimal("49.99"), 10, true, null, LocalDateTime.now());
when(productService.create(any())).thenReturn(created);

mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("New Product"));
}

Teste 6: POST /api/products - Erro de Validação​

@Test
@DisplayName("POST /api/products - Deve retornar 400 se dados inválidos")
void create_WithInvalidData_ShouldReturn400() throws Exception {
ProductRequest invalid = new ProductRequest();
invalid.setName(""); // Inválido: em branco
invalid.setPrice(new BigDecimal("-10")); // Inválido: negativo

mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(invalid)))
.andExpect(status().isBadRequest());
}

Teste 7: POST sem Content-Type​

@Test
@DisplayName("POST /api/products - Deve retornar 415 sem Content-Type")
void create_WithoutContentType_ShouldReturn415() throws Exception {
mockMvc.perform(post("/api/products")
.content("{\"name\":\"Test\"}"))
.andExpect(status().isUnsupportedMediaType());
}

Parte 5: Testes PUT​

Teste 8: PUT /api/products/{id} - Sucesso​

@Test
@DisplayName("PUT /api/products/{id} - Deve atualizar o produto")
void update_WhenExists_ShouldReturnUpdated() throws Exception {
// TODO: Implementar
}

Teste 9: PUT /api/products/{id} - Not Found​

@Test
@DisplayName("PUT /api/products/{id} - Deve retornar 404 se não encontrado")
void update_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implementar
}

Parte 6: Testes DELETE​

Teste 10: DELETE /api/products/{id} - Sucesso​

@Test
@DisplayName("DELETE /api/products/{id} - Deve remover o produto")
void delete_WhenExists_ShouldReturn204() throws Exception {
when(productService.delete(1L)).thenReturn(true);

mockMvc.perform(delete("/api/products/{id}", 1))
.andExpect(status().isNoContent());

verify(productService).delete(1L);
}

Teste 11: DELETE /api/products/{id} - Not Found​

@Test
@DisplayName("DELETE /api/products/{id} - Deve retornar 404 se não encontrado")
void delete_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implementar
}

Parte 7: Testes com Autenticação​

Configuração Security​

@WebMvcTest(ProductController.class)
@Import(SecurityConfig.class) // Importar a config de segurança
class SecuredProductControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private ProductService productService;

@Test
@WithMockUser(roles = "USER")
void getAll_AsUser_ShouldReturnProducts() throws Exception {
when(productService.findAll()).thenReturn(List.of());

mockMvc.perform(get("/api/products"))
.andExpect(status().isOk());
}

@Test
void getAll_AsAnonymous_ShouldReturn401() throws Exception {
mockMvc.perform(get("/api/products"))
.andExpect(status().isUnauthorized());
}

@Test
@WithMockUser(roles = "ADMIN")
void delete_AsAdmin_ShouldSucceed() throws Exception {
when(productService.delete(1L)).thenReturn(true);

mockMvc.perform(delete("/api/products/{id}", 1))
.andExpect(status().isNoContent());
}

@Test
@WithMockUser(roles = "USER")
void delete_AsUser_ShouldReturn403() throws Exception {
mockMvc.perform(delete("/api/products/{id}", 1))
.andExpect(status().isForbidden());
}
}

Parte 8: Gabarito​

Clique para ver o gabarito
@WebMvcTest(ProductController.class)
class ProductControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private ProductService productService;

private Product sampleProduct;

@BeforeEach
void setUp() {
sampleProduct = new Product(1L, "Laptop", "High-end",
new BigDecimal("999.99"), 10, true, null, LocalDateTime.now());
}

@Test
void getById_WhenNotExists_ShouldReturn404() throws Exception {
when(productService.findById(999L)).thenReturn(Optional.empty());

mockMvc.perform(get("/api/products/{id}", 999))
.andExpect(status().isNotFound());
}

@Test
void search_ShouldFilterProducts() throws Exception {
when(productService.search(eq("Laptop"), any(), any()))
.thenReturn(List.of(sampleProduct));

mockMvc.perform(get("/api/products/search")
.param("name", "Laptop")
.param("minPrice", "500")
.param("maxPrice", "1500"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(1));
}

@Test
void update_WhenExists_ShouldReturnUpdated() throws Exception {
ProductRequest request = new ProductRequest();
request.setName("Updated");
request.setPrice(new BigDecimal("1099.99"));
request.setStock(5);

Product updated = new Product(1L, "Updated", null,
new BigDecimal("1099.99"), 5, true, null, LocalDateTime.now());
when(productService.update(eq(1L), any())).thenReturn(Optional.of(updated));

mockMvc.perform(put("/api/products/{id}", 1)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Updated"));
}

@Test
void update_WhenNotExists_ShouldReturn404() throws Exception {
ProductRequest request = new ProductRequest();
request.setName("Test");
request.setPrice(new BigDecimal("100"));

when(productService.update(eq(999L), any())).thenReturn(Optional.empty());

mockMvc.perform(put("/api/products/{id}", 999)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isNotFound());
}

@Test
void delete_WhenNotExists_ShouldReturn404() throws Exception {
when(productService.delete(999L)).thenReturn(false);

mockMvc.perform(delete("/api/products/{id}", 999))
.andExpect(status().isNotFound());
}
}

Verificação​

mvn test -Dtest=ProductControllerTest

Checklist​

  • Todos os endpoints CRUD testados
  • Status codes verificados (200, 201, 204, 400, 404)
  • Respostas JSON validadas
  • Headers verificados (Location para POST)
  • Testes de validação
  • Testes com autenticação (opcional)

🎯 Módulo Concluído!​

Parabéns! Você concluiu o Módulo 9 - Testes com Spring Boot.

Resumo:

  • Capítulo 1: Introdução aos Testes
  • Capítulo 2: JUnit 5
  • Capítulo 3: Mockito
  • Capítulo 4: Testes de Integração
  • Capítulo 5: Testes REST API
  • TP9.1: Testes Unitários Service
  • TP9.2: Testes Integração Repository
  • TP9.3: Testes REST API Controller

➡️ Voltar ao Módulo 9


⬅️ Voltar ao Plano de Curso