This article demonstrates testing the DELETE API for product inventory, including adding, retrieving, and deleting a product while verifying status codes.
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.
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.