Golang Testing — JSON Responses with Gin

Craig Childs
2 min readApr 3, 2017

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:

package mainimport (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := SetupRouter()
router.Run()
}
func SetupRouter() *gin.Engine {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hello": "world",
})
})

return router
}

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

package mainimport (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
req, _ := http.NewRequest(method, path, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestHelloWorld(t *testing.T) {
// Build our expected body
body := gin.H{
"hello": "world",
}
// Grab our router
router := SetupRouter()
// Perform a GET request with that handler.
w := performRequest(router, "GET", "/")
// Assert we encoded correctly,
// the request gives a 200
assert.Equal(t, http.StatusOK, w.Code)
// Convert the JSON response to a map
var response map[string]string
err := json.Unmarshal([]byte(w.Body.String()), &response)
// Grab the value & whether or not it exists
value, exists := response["hello"]
// Make some assertions on the correctness of the response.
assert.Nil(t, err)
assert.True(t, exists)
assert.Equal(t, body["hello"], value)
}

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

--

--

Craig Childs

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