TP9.3 - Tests REST API con MockMvc
Objetivos del TP
En este TP, usted va a:
- ✅ Probar un controller REST completo con MockMvc
- ✅ Validar las solicitudes GET, POST, PUT, DELETE
- ✅ Probar las respuestas JSON con JSONPath
- ✅ Probar los errores (404, 400, 500)
- ✅ Probar con autenticación
Duración estimada: 1h30
Contexto
Usted tiene un ProductController que expone una API REST CRUD. Debe probar todos los endpoints con MockMvc.
Parte 1: El Controller a Probar
@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: Configuración de las Pruebas
@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: Pruebas GET
Prueba 1: GET /api/products
@Test
@DisplayName("GET /api/products - Debe devolver la lista de productos")
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"));
}
Prueba 2: GET /api/products/{id} - Éxito
@Test
@DisplayName("GET /api/products/{id} - Debe devolver el producto")
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));
}
Prueba 3: GET /api/products/{id} - No Encontrado
@Test
@DisplayName("GET /api/products/{id} - Debe devolver 404 si no se encuentra")
void getById_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implementar
}
Prueba 4: GET /api/products/search
@Test
@DisplayName("GET /api/products/search - Debe filtrar los productos")
void search_ShouldFilterProducts() throws Exception {
// TODO: Implementar con params
}
Parte 4: Pruebas POST
Prueba 5: POST /api/products - Éxito
@Test
@DisplayName("POST /api/products - Debe crear un producto")
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"));
}
Prueba 6: POST /api/products - Error de Validación
@Test
@DisplayName("POST /api/products - Debe devolver 400 si los datos son inválidos")
void create_WithInvalidData_ShouldReturn400() throws Exception {
ProductRequest invalid = new ProductRequest();
invalid.setName(""); // Inválido: vacío
invalid.setPrice(new BigDecimal("-10")); // Inválido: negativo
mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(invalid)))
.andExpect(status().isBadRequest());
}
Prueba 7: POST sin Content-Type
@Test
@DisplayName("POST /api/products - Debe devolver 415 sin Content-Type")
void create_WithoutContentType_ShouldReturn415() throws Exception {
mockMvc.perform(post("/api/products")
.content("{\"name\":\"Test\"}"))
.andExpect(status().isUnsupportedMediaType());
}
Parte 5: Pruebas PUT
Prueba 8: PUT /api/products/{id} - Éxito
@Test
@DisplayName("PUT /api/products/{id} - Debe actualizar el producto")
void update_WhenExists_ShouldReturnUpdated() throws Exception {
// TODO: Implementar
}
Prueba 9: PUT /api/products/{id} - No Encontrado
@Test
@DisplayName("PUT /api/products/{id} - Debe devolver 404 si no se encuentra")
void update_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implementar
}
Parte 6: Pruebas DELETE
Prueba 10: DELETE /api/products/{id} - Éxito
@Test
@DisplayName("DELETE /api/products/{id} - Debe eliminar el producto")
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);
}
Prueba 11: DELETE /api/products/{id} - No Encontrado
@Test
@DisplayName("DELETE /api/products/{id} - Debe devolver 404 si no se encuentra")
void delete_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implementar
}
Parte 7: Pruebas con Autenticación
Configuración Security
@WebMvcTest(ProductController.class)
@Import(SecurityConfig.class) // Importar la configuración de seguridad
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: Solucionario
Haga clic para ver el solucionario
@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());
}
}
Verificación
mvn test -Dtest=ProductControllerTest
Checklist
- Todos los endpoints CRUD probados
- Códigos de estado verificados (200, 201, 204, 400, 404)
- Respuestas JSON validadas
- Headers verificados (Location para POST)
- Pruebas de validación
- Pruebas con autenticación (opcional)
🎯 ¡Módulo Terminado!
¡Felicitaciones! Ha completado el Módulo 9 - Pruebas con Spring Boot.
Resumen:
- Capítulo 1: Introducción a las Pruebas
- Capítulo 2: JUnit 5
- Capítulo 3: Mockito
- Capítulo 4: Pruebas de Integración
- Capítulo 5: Pruebas REST API
- TP9.1: Pruebas Unitarias Service
- TP9.2: Pruebas Integración Repository
- TP9.3: Pruebas REST API Controller