Skip to content

Commit 78c3cff

Browse files
committed
Add tests for product creation with validation and error handling
1 parent 58d4c26 commit 78c3cff

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/main/java/com/productstore/service/controller/ProductController.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,17 @@ public ResponseEntity<Product> createProduct(@Valid @RequestBody Product product
3636

3737
// List all Products
3838

39+
3940

4041
// Read a Product
4142

43+
4244

4345
// Update a Product
4446

47+
4548

4649
// Delete a Product
50+
4751

4852
}

src/test/java/com/productstore/service/controller/ProductControllerTest.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,54 @@ private Product createProductFixture() {
5252
product.setCategory(Product.Category.CLOTHS);
5353
return product;
5454
}
55+
56+
57+
58+
@Test
59+
public void testCreateProduct() throws Exception {
60+
// Create a product for testing
61+
Product product = createProductFixture();
62+
product.setId(null); // ID should be null for creation
63+
64+
// Create the expected result (product with ID assigned)
65+
Product createdProduct = createProductFixture();
66+
createdProduct.setId(1L);
67+
68+
// Mock service behavior
69+
when(productService.create(any(Product.class))).thenReturn(createdProduct);
70+
71+
// Make the request and validate
72+
mockMvc.perform(post("/products")
73+
.contentType(MediaType.APPLICATION_JSON)
74+
.content(objectMapper.writeValueAsString(product)))
75+
.andExpect(status().isCreated())
76+
.andExpect(header().string("Location", containsString("/products/1")))
77+
.andExpect(jsonPath("$.id").value(createdProduct.getId()))
78+
.andExpect(jsonPath("$.name").value(createdProduct.getName()))
79+
.andExpect(jsonPath("$.description").value(createdProduct.getDescription()))
80+
.andExpect(jsonPath("$.price").value(createdProduct.getPrice().doubleValue()))
81+
.andExpect(jsonPath("$.available").value(createdProduct.getAvailable()))
82+
.andExpect(jsonPath("$.category").value(createdProduct.getCategory().toString()));
83+
84+
verify(productService).create(any(Product.class));
85+
}
86+
87+
@Test
88+
public void testCreateProductWithValidationError() throws Exception {
89+
// Create an invalid product (missing required fields)
90+
Product invalidProduct = new Product();
91+
// Name and description are required but not set
92+
93+
// Make the request and validate
94+
mockMvc.perform(post("/products")
95+
.contentType(MediaType.APPLICATION_JSON)
96+
.content(objectMapper.writeValueAsString(invalidProduct)))
97+
.andExpect(status().isBadRequest());
98+
99+
// Verify service was never called with invalid data
100+
verify(productService, never()).create(any(Product.class));
101+
}
102+
55103

56104

57105
}

0 commit comments

Comments
 (0)