繁体   English   中英

在 Golang 中单元测试 http json 响应

[英]Unit testing http json response in Golang

我使用gin作为我的 http 服务器,并在 json 中发回一个空数组作为我的响应:

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

我得到的结果 json 字符串是"[]\n" 换行符由 json Encoder 对象添加,请参见此处

使用goconvey ,我可以像测试我的 json

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

但是有没有比仅仅为所有字符串添加换行符更好的方法来生成预期的 json 字符串?

您应该首先将响应的主体解组为结构并与结果对象进行比较。 例子:

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

您可能会发现jsonassert很有用。 它在标准库之外没有依赖项,并允许您验证 JSON 字符串在语义上是否等同于您期望的 JSON 字符串。

在你的情况下:

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

它可以处理任何形式的 JSON,并且有非常友好的断言错误消息。

免责声明:我写了这个包。

我是这样弄的。 因为我不想包含额外的库。

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