Group testing json HTTP response in Golang

I use ginas my http server and send an empty array to json as an answer:

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

The resulting json string I get is equal to "[]\n". A new line has been added by the json Encoder object, see here .

Using goconvey, I could check my json as

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

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

+5
source share
3 answers

Lift the body into the structure and use the Gocheck DeepEquals https://godoc.org/launchpad.net/gocheck

+2
source

. :

result := []string{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
    log.Fatalln(err)
}
So(len(result), ShouldEqual, 0)
+2

You may find jsonassert useful. It has no dependencies outside the standard library and allows you to verify that JSON strings are semantically equivalent to the expected JSON string.

A case of you:

// white space is ignored, no need for \n
jsonassert.New(t).Assertf(response.Body().String(), "[]")

It can handle any form of JSON and has very friendly approval error messages.

Disclaimer: I wrote this package.

0
source

Source: https://habr.com/ru/post/1615472/


All Articles