Skip to main content
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.

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:
  1. Clearing the table: Ensure the database table is empty before running the test.
  2. Preparing the payload: A JSON payload representing a new product is created.
  3. 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.NewRequest function.
  4. 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.
Below is the test function for the POST API:

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 with interface{} 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 the createProduct 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 the product 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 as 1 (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.

Conclusion

This article demonstrated how to test the POST API for creating a product. We covered the creation of helper functions, setting up the test request, verifying the response, and handling JSON number conversion in Go. Next, we will explore testing the DELETE API. Stay tuned for more detailed tutorials on API testing.

References

Watch Video