In this article, I want to show how to write a test for HTTP handlers that interact with the database using the httptest package.
We will look at how to inject the necessary dependencies and mock the database calls.
https://pkg.go.dev/net/http/httptest
Go has an amazing testing package in its standard library httptest package. It provides a small set of structures and functions for HTTP testing.
Let’s have a look at how you can use the httptest package and build better end-to-end and http tests for your Go handlers.
First, creates a directory and initialize thego.mod
file:
mkdir test-handlers-gogo mod init
Here is the basic handler that returns an HTTP 200 (OK) status code and a ‘hello world!’ message. This is our handler:
and the test:
We just construct a request, a response, and pass them as a parameter to our handler function. Then check the status code and response body.
As you can see, Go’stesting andhttptest packages make testing our handlers extremely simple.
I hope you are now clear about the usage httptest package to test handlers. That’s the main idea. But more clarifying, I give an example on CRUD API.
I created a simple CRUD API that has these endpoints:
/v1/book
to create a new book/v1/book
gets all book/v1/book/:id
delete book according to the given id/v1/book/:id
update book informationI don’t show how to build the API, you can checkhere the API. We will just write a test for it.
Let’s start with mocking the database calls:
Let’s define structs for test cases:
Test Handler (POST Method)
Now, we can write a test for AddBookHandler:
Test Handler (Delete Method + Parameter)
When sending a request to the DeleteBook endpoint, we need an id parameter. Let’s look at how we can add parameters while testing:
The rest of the handler tests are available on theGitHub repository.
→ Have a Good Day ←