TP9.3 - Tests REST API avec MockMvc
Objectifs du TP
Dans ce TP, vous allez:
- ✅ Tester un controller REST complet avec MockMvc
- ✅ Valider les requêtes GET, POST, PUT, DELETE
- ✅ Tester les réponses JSON avec JSONPath
- ✅ Tester les erreurs (404, 400, 500)
- ✅ Tester avec authentification
Durée estimée: 1h30
Contexte
Vous avez un ProductController qui expose une API REST CRUD. Vous devez tester tous les endpoints avec MockMvc.
Partie 1: Le Controller à Tester
@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;
}
Partie 2: Configuration des Tests
@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());
}
}
Partie 3: Tests GET
Test 1: GET /api/products
@Test
@DisplayName("GET /api/products - Devrait retourner la liste des produits")
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"));
}
Test 2: GET /api/products/{id} - Succès
@Test
@DisplayName("GET /api/products/{id} - Devrait retourner le produit")
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));
}
Test 3: GET /api/products/{id} - Not Found
@Test
@DisplayName("GET /api/products/{id} - Devrait retourner 404 si non trouvé")
void getById_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implémenter
}
Test 4: GET /api/products/search
@Test
@DisplayName("GET /api/products/search - Devrait filtrer les produits")
void search_ShouldFilterProducts() throws Exception {
// TODO: Implémenter avec params
}
Partie 4: Tests POST
Test 5: POST /api/products - Succès
@Test
@DisplayName("POST /api/products - Devrait créer un produit")
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"));
}
Test 6: POST /api/products - Validation Error
@Test
@DisplayName("POST /api/products - Devrait retourner 400 si données invalides")
void create_WithInvalidData_ShouldReturn400() throws Exception {
ProductRequest invalid = new ProductRequest();
invalid.setName(""); // Invalid: blank
invalid.setPrice(new BigDecimal("-10")); // Invalid: negative
mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(invalid)))
.andExpect(status().isBadRequest());
}
Test 7: POST sans Content-Type
@Test
@DisplayName("POST /api/products - Devrait retourner 415 sans Content-Type")
void create_WithoutContentType_ShouldReturn415() throws Exception {
mockMvc.perform(post("/api/products")
.content("{\"name\":\"Test\"}"))
.andExpect(status().isUnsupportedMediaType());
}
Partie 5: Tests PUT
Test 8: PUT /api/products/{id} - Succès
@Test
@DisplayName("PUT /api/products/{id} - Devrait mettre à jour le produit")
void update_WhenExists_ShouldReturnUpdated() throws Exception {
// TODO: Implémenter
}
Test 9: PUT /api/products/{id} - Not Found
@Test
@DisplayName("PUT /api/products/{id} - Devrait retourner 404 si non trouvé")
void update_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implémenter
}
Partie 6: Tests DELETE
Test 10: DELETE /api/products/{id} - Succès
@Test
@DisplayName("DELETE /api/products/{id} - Devrait supprimer le produit")
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);
}
Test 11: DELETE /api/products/{id} - Not Found
@Test
@DisplayName("DELETE /api/products/{id} - Devrait retourner 404 si non trouvé")
void delete_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implémenter
}
Partie 7: Tests avec Authentification
Configuration Security
@WebMvcTest(ProductController.class)
@Import(SecurityConfig.class) // Importer la config security
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());
}
}
Partie 8: Solutionnaire
Cliquer pour voir le solutionnaire
@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());
}
}
Vérification
mvn test -Dtest=ProductControllerTest
Checklist
- Tous les endpoints CRUD testés
- Status codes vérifiés (200, 201, 204, 400, 404)
- JSON responses validées
- Headers vérifiés (Location pour POST)
- Tests de validation
- Tests avec authentification (optionnel)
🎯 Module Terminé!
Félicitations! Vous avez complété le Module 9 - Tests avec Spring Boot.
Récapitulatif:
- Chapitre 1: Introduction aux Tests
- Chapitre 2: JUnit 5
- Chapitre 3: Mockito
- Chapitre 4: Tests d'Intégration
- Chapitre 5: Tests REST API
- TP9.1: Tests Unitaires Service
- TP9.2: Tests Intégration Repository
- TP9.3: Tests REST API Controller