In this article, we demonstrate how to test the POST API endpoint for creating a new product. The guide covers writing helper functions, constructing the request payload, sending the request, and verifying the API response.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Helper Functions for Testing
First, we define helper functions to verify status codes and to send HTTP requests. These functions simplify the testing process by encapsulating common operations.Testing the POST API
The test for the POST API for creating a product involves several key steps:- Clearing the table: Ensure the database table is empty before running the test.
- Preparing the payload: A JSON payload representing a new product is created.
- Creating and sending the HTTP POST request: The JSON payload is converted into a byte slice and wrapped in a bytes buffer, as required by the
http.NewRequestfunction. - Verifying the response: The response status is checked to confirm if the product was created successfully.
The request header is explicitly set to
"application/json" to ensure the server processes the payload correctly.Verifying the Response Payload
After executing the request, we inspect the response payload by unmarshaling the JSON into a map. This verification ensures that the product details in the response match the expected values. Note that when JSON is unmarshaled into a map withinterface{} values, numbers convert to float64 by default.
Running the Tests
Execute the tests using the command below to confirm that both the POST and GET API endpoints are functioning as expected:API Implementation Snippet
For additional context, here is an excerpt from the API implementation where thecreateProduct method is defined. This method inserts the new product into the database and sends the appropriate HTTP response:
Product Structure Definition
Below is the structure definition for theproduct type. This type represents individual items in the inventory:
Handling JSON Number Conversion
An important detail is how JSON numbers are unmarshaled. Initially, an error occurred because the expected quantity was specified as1 (an integer) while the unmarshaled value was 1.0 (a float64). Adjusting the expected value to 1.0 resolved the issue, and the test passed successfully.