Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing http json response in Golang

Tags:

json

go

I am using gin as my http server and sending back an empty array in json as my response:

c.JSON(http.StatusOK, []string{})

The resulting json string I get is "[]\n". The newline is added by the json Encoder object, see here.

Using goconvey, I could test my json like

So(response.Body.String(), ShouldEqual, "[]\n")

But is there a better way to generate the expected json string than just adding a newline to all of them?

like image 797
Derek Avatar asked Nov 11 '15 20:11

Derek


2 Answers

You should first unmarshal the body of the response into a struct and compare against the resulting object. Example:

result := []string{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
    log.Fatalln(err)
}
So(len(result), ShouldEqual, 0)
like image 183
vially Avatar answered Nov 14 '22 21:11

vially


Unmarshal the body into a struct and the use Gocheck's DeepEquals https://godoc.org/launchpad.net/gocheck

like image 31
Karl Avatar answered Nov 14 '22 19:11

Karl