@@ -52,6 +52,54 @@ private Product createProductFixture() {
52
52
product .setCategory (Product .Category .CLOTHS );
53
53
return product ;
54
54
}
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
+
55
103
56
104
57
105
}
0 commit comments