Update Application Initialization
Before testing, we need to modify the application initialization method to dynamically accept database credentials (DB user, DB password, and DB name) instead of relying on hardcoded constants. This change allows us to specify different credentials during testing. Below is the original initialization method:Initialise method as follows:
main.go file, initialize the application by passing the database constants:
Using dynamic credentials improves flexibility by letting you create separate configurations for production and testing environments.
Update Route Handlers
Modify Create Product Handler
ThecreateProduct handler originally returns an HTTP status code of 200 (OK) when a product is successfully created. However, according to RESTful best practices, a 201 (Created) response is more appropriate for resource creation. Below is the existing implementation:
createProduct handler to return a 201 (Created) status code:
Additional Route Handler Implementations
Below are implementations for other route handlers used to retrieve products:Testing Setup
To test the API, create a separate test file (e.g.,app_test.go). In this file, declare your application variable and use the test main function to initialize the application for testing. The test main function, introduced in Go 1.4, is executed to set up and run all tests within the package. Note that the test main function should appear only once per package.
Below is an example of initializing your app variable in the test main function:
Using a dedicated test database ensures that your testing operations do not affect live production data. Always isolate your testing environment from production.
Summary
This article explained:- How to modify the application initialization to dynamically accept database credentials.
- Updating the
createProducthandler to return an HTTP 201 status code for resource creation. - Setting up a dedicated test environment to safely run API tests.