Golang Testing — JSON Responses with Gin

Recently I’ve been implementing a small side project in Go with Gin. I know how easy it is to setup tests with Go, but I was very surprised not many people had covered examples of how to test the JSON responses for your APIs. With Gin specifically.

I discovered, it’s quite simple.

First we want an endpoint to test so here we go. The following would return a simple {"hello":"world"} JSON response. On a GET request to / in a file called main.go put:

Then following conventions with Go we’ll create another file for tests main_test.go in the same directory:

Running go test in the same directory as these files will run the tests. I hope this is of use to you, I know it took me a while to find any substantial examples; for now this is the way I’m going to be verifying my JSON responses

Photo by Agence Olloweb on Unsplash

Update: I recently published another article on testing, how to mock Redis, you can check it out here: https://medium.com/@craigchilds94/golang-testing-mocking-redis-b48d09386c70

Multi-pronged web developer with a passion for cutting edge tooling! https://craigchilds.dev