This article demonstrates testing the DELETE API for product inventory, including adding, retrieving, and deleting a product while verifying status codes.
In this article, we demonstrate how to test the DELETE API for our product inventory. The testing process consists of the following steps:
Clear the product table.
Add a new product using the POST API.
Retrieve the product with a GET API to verify its creation.
Delete the product using the DELETE API.
Attempt to retrieve the deleted product to ensure it has been removed.
Below is the enhanced and consolidated test code that enforces consistent naming and proper status code verification.
The following test demonstrates how to clear existing data, add a product named “connector”, verify its addition, and then delete it. Finally, it confirms that a GET request after deletion returns a 404 Not Found status.
Copy
Ask AI
func TestDeleteProduct(t *testing.T) { // Clear existing data. clearTable() // Add a product "connector" with quantity 10 and price 10. addProduct("connector", 10, 10) // Retrieve the product using GET request. req, _ := http.NewRequest("GET", "/product/1", nil) response := sendRequest(req) checkStatusCode(t, http.StatusOK, response.Code) // Validate the retrieved product details. var m map[string]interface{} json.Unmarshal(response.Body.Bytes(), &m) if m["name"] != "connector" { t.Errorf("Expected name: %v, Got: %v", "connector", m["name"]) } if m["quantity"] != 10.0 { t.Errorf("Expected quantity: %v, Got: %v", 10.0, m["quantity"]) } // Delete the product using DELETE request. req, _ = http.NewRequest("DELETE", "/product/1", nil) response = sendRequest(req) checkStatusCode(t, http.StatusOK, response.Code) // Try to retrieve the deleted product. req, _ = http.NewRequest("GET", "/product/1", nil) response = sendRequest(req) // Expect a 404 Not Found status since the product has been deleted. checkStatusCode(t, http.StatusNotFound, response.Code)}
In the application code (for example, in app.go), the DELETE API must correctly handle the removal of a product by its ID. Following the deletion, a GET request for the same product ID should yield a 404 status, confirming the deletion was successful.
When running the tests using go test, you might encounter output similar to the following if there is a discrepancy between expected and actual status codes:
In this log, a 404 response was received instead of the expected 200 OK status before deletion. The improved test code now correctly checks for a 404 Not Found status after the product has been deleted.All tests should pass once the DELETE API and the status code validations are implemented correctly.