How to Create API Unit Tests with Code Coverage in Golang.
Unit tests are an important part of the software development process as they allow developers to verify that the individual units of their code are working as expected. In the context of an API, unit tests can be used to verify that the API is functioning correctly and returning the expected responses to requests. Code coverage is a measure of how much of the code is being tested by the unit tests. In this article, we will look at how to create API unit tests with code coverage in Go (also known as Golang).
Before we get started, it’s important to note that code coverage should not be the only measure of the quality of your tests. It is just one tool that can be used to help identify areas of the code that are not being thoroughly tested.
Setting up the project
To get started, we need to create a new Go project and install the necessary dependencies.
First, create a new directory for your project and navigate to it:
mkdir my-project
cd my-project
Next, create a go.mod
file which will define the dependencies for your project:
go mod init my-project
Now, we need to install the necessary packages for our API and the testing tools. In this example, we will be using the gin
package for the API and the testify
package for the testing tools.
go get github.com/gin-gonic/gin
go get github.com/stretchr/testify/assert
Writing the API
Now that we have our project set up, we can start writing the API. In this example, we will create a simple API that has a single endpoint which returns a list of strings.
Create a new file called main.go
and add the following code:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/items", func(c *gin.Context) {
items := []string{"item1", "item2", "item3"}
c.JSON(200, items)
})
router.Run()
}
This code creates a new router using the gin
package and defines a single endpoint at the path /items
. When a request is made to this endpoint, the server will return a JSON array of strings.
Writing the unit tests
Now that we have our API set up, we can start writing the unit tests. In Go, unit tests are typically placed in a file with the same name as the file being tested, but with a _test
suffix. So for our main.go
file, we will create a file called main_test.go
.
In the main_test.go
file, we can create a test function for each unit we want to test. In this case, we want to test the /items
endpoint, so we will create a test function called TestItemsEndpoint
.
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestItemsEndpoint(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/items", nil)
router.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
assert.JSONEq(t, `["item1", "item2", "item3"]`, w.Body.String())
}
This test function creates a new httptest.ResponseRecorder
which will record the response from the API. It then creates a new http.Request
and sends it to the API using the router.ServeHTTP
function.
The test then uses the assert
package to check that the response has a status code of 200
and that the response body is the JSON array of strings we expect.
Running the tests
To run the tests, we can use the go test
command:
go test
This will run all the tests in the project and output the results. If all the tests pass, you should see a message like this:
PASS
ok my-project 0.005s
Generating code coverage reports
To generate a code coverage report, we can use the go test
command with the -cover
flag and the -coverprofile
flag to specify the file where the report should be saved.
go test -cover -coverprofile=coverage.out
This will generate a file called coverage.out
with the code coverage data. To view the report, we can use the go tool cover
command:
go tool cover -func=coverage.out
This will output a summary of the code coverage, showing the percentage of lines, statements, and functions covered by the tests.
To view a detailed report showing which specific lines of code are covered, we can use the go tool cover
command with the -html
flag and specify the file where the HTML report should be saved:
go tool cover -html=coverage.out -o coverage.html
This will generate an HTML file called coverage.html
which can be opened in a web browser. The report will show a color-coded view of the code, with lines in green indicating that they are covered by tests and lines in red indicating that they are not covered.
Conclusion
In this article, we have seen how to create API unit tests with code coverage in Go. By following these steps, you can ensure that your API is thoroughly tested and that you have a clear understanding of which parts of your code are being covered by the tests. Code coverage is just one tool that can be used to help improve the quality of your tests, but it is important to remember that it should not be the only measure of the quality of your tests. It is important to also consider the quality and effectiveness of the tests themselves.