简体   繁体   English

在 Golang 中单元测试 http json 响应

[英]Unit testing http json response in Golang

I am using gin as my http server and sending back an empty array in json as my response:我使用gin作为我的 http 服务器,并在 json 中发回一个空数组作为我的响应:

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

The resulting json string I get is "[]\n" .我得到的结果 json 字符串是"[]\n" The newline is added by the json Encoder object, seehere .换行符由 json Encoder 对象添加,请参见此处

Using goconvey , I could test my json like使用goconvey ,我可以像测试我的 json

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?但是有没有比仅仅为所有字符串添加换行符更好的方法来生成预期的 json 字符串?

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)

将主体解组为结构并使用 Gocheck 的 DeepEquals https://godoc.org/launchpad.net/gocheck

You may find jsonassert useful.您可能会发现jsonassert很有用。 It has no dependencies outside the standard library and allows you to verify that JSON strings are semantically equivalent to a JSON string you expect.它在标准库之外没有依赖项,并允许您验证 JSON 字符串在语义上是否等同于您期望的 JSON 字符串。

In your case:在你的情况下:

// 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 assertion error messages.它可以处理任何形式的 JSON,并且有非常友好的断言错误消息。

Disclaimer: I wrote this package.免责声明:我写了这个包。

I made it this way.我是这样弄的。 Because I don't want to include an extra library.因为我不想包含额外的库。

tc := testCase{
    w: httptest.NewRecorder(),
    wantResponse: mustJson(t, map[string]string{"message": "unauthorized"}),
}
...

if tc.wantResponse != tc.w.Body.String() {
    t.Errorf("want %s, got %s", tt.wantResponse, tt.w.Body.String())
}

...
func mustJson(t *testing.T, v interface{}) string {
    t.Helper()
    out, err := json.Marshal(v)
    if err != nil {
        t.Fatal(err)
    }
    return string(out)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM