TP9.3 - REST API Tests with MockMvc
Objectives of the Lab
In this lab, you will:
- ✅ Test a complete REST controller with MockMvc
- ✅ Validate GET, POST, PUT, DELETE requests
- ✅ Test JSON responses with JSONPath
- ✅ Test errors (404, 400, 500)
- ✅ Test with authentication
Estimated duration: 1h30
Context
You have a ProductController that exposes a CRUD REST API. You need to test all endpoints with MockMvc.
Part 1: The Controller to Test
@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;
}
Part 2: Test Configuration
@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());
}
}
Part 3: GET Tests
Test 1: GET /api/products
@Test
@DisplayName("GET /api/products - Should return the list of products")
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} - Success
@Test
@DisplayName("GET /api/products/{id} - Should return the product")
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} - Should return 404 if not found")
void getById_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implement
}
Test 4: GET /api/products/search
@Test
@DisplayName("GET /api/products/search - Should filter products")
void search_ShouldFilterProducts() throws Exception {
// TODO: Implement with params
}
Part 4: POST Tests
Test 5: POST /api/products - Success
@Test
@DisplayName("POST /api/products - Should create a product")
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 - Should return 400 if invalid data")
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 without Content-Type
@Test
@DisplayName("POST /api/products - Should return 415 without Content-Type")
void create_WithoutContentType_ShouldReturn415() throws Exception {
mockMvc.perform(post("/api/products")
.content("{\"name\":\"Test\"}"))
.andExpect(status().isUnsupportedMediaType());
}
Part 5: PUT Tests
Test 8: PUT /api/products/{id} - Success
@Test
@DisplayName("PUT /api/products/{id} - Should update the product")
void update_WhenExists_ShouldReturnUpdated() throws Exception {
// TODO: Implement
}
Test 9: PUT /api/products/{id} - Not Found
@Test
@DisplayName("PUT /api/products/{id} - Should return 404 if not found")
void update_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implement
}
Part 6: DELETE Tests
Test 10: DELETE /api/products/{id} - Success
@Test
@DisplayName("DELETE /api/products/{id} - Should delete the product")
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} - Should return 404 if not found")
void delete_WhenNotExists_ShouldReturn404() throws Exception {
// TODO: Implement
}
Part 7: Tests with Authentication
Security Configuration
@WebMvcTest(ProductController.class)
@Import(SecurityConfig.class) // Import security config
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());
}
}
Part 8: Solution
Click to view the solution
@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());
}
}
Verification
mvn test -Dtest=ProductControllerTest
Checklist
- All CRUD endpoints tested
- Status codes verified (200, 201, 204, 400, 404)
- JSON responses validated
- Headers verified (Location for POST)
- Validation tests
- Tests with authentication (optional)
🎯 Module Completed!
Congratulations! You have completed Module 9 - Testing with Spring Boot.
Summary:
- Chapter 1: Introduction to Testing
- Chapter 2: JUnit 5
- Chapter 3: Mockito
- Chapter 4: Integration Tests
- Chapter 5: REST API Tests
- TP9.1: Unit Tests Service
- TP9.2: Integration Tests Repository
- TP9.3: REST API Controller Tests