我正在为一个宁静的 api 编写单元测试,并希望确保得到预期的响应。如何去掉预期字符串文字末尾的“\n”?我正在使用 stethr 的 testify 包。我曾尝试使用字符串 TrimSuffix、TrimRight 函数,但没有成功。func TestGetConfig(t *testing.T) { testServer := initTestServer(t) req, err := http.NewRequest("GET", "/api/config", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(testServer.getConfig) handler.ServeHTTP(rr, req) //Check the status code is what we expect if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //Check the response body is what we expect. expected := `{"domain":"","ip":"","redirect_key":"mj","redirect_url":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","verification_key":"yp","verification_token":"5a62"}` expected = strings.TrimSuffix(expected, "\n") assert.Equal(t, rr.Body.String(), expected)}我希望测试能够通过,但它却失败了,并将其作为输出。Error Trace: config_test.go:94 Error: Not equal: expected: "{\"domain\":\"\",\"ip\":\"\",\"redirect_key\":\"mj\",\"redirect_url\":\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\",\"verification_key\":\"yp\",\"verification_token\":\"5a62\"}\n" actual : "{\"domain\":\"\",\"ip\":\"\",\"redirect_key\":\"mj\",\"redirect_url\":\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\",\"verification_key\":\"yp\",\"verification_token\":\"5a62\"}"
2 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
您正在从字符串而不是实际的响应正文中删除一个不存在的"\n"
字符。expected
"\n"
但更简单的方法是只在字符串中包含expected
。这样,预期的字符串实际上就是您所期望的。
守候你守候我
TA贡献1802条经验 获得超10个赞
参数顺序错误。
这是
assert.Equal(t, rr.Body.String(), expected)
它应该是
assert.Equal(t, expected, rr.Body.String())
- 2 回答
- 0 关注
- 82 浏览
添加回答
举报
0/150
提交
取消