如何修复原始字符串文字上的失败断言

时间:2019-01-08 08:06:27

标签: go

我正在为一个宁静的api编写单元测试,并希望确保获得预期的响应。如何消除期望的字符串文字末尾的“ \ n”?

我正在使用stetchr的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 个答案:

答案 0 :(得分:2)

参数顺序错误。

assert.Equal(t, rr.Body.String(), expected)

应该是

assert.Equal(t, expected, rr.Body.String())

请参见Equal method documentatin

您正在调整错误的值。

答案 1 :(得分:2)

您正在修剪"\n"字符串中不存在的expected字符,而不是实际的响应正文。

但是更简单的方法是仅在"\n"字符串中包含expected。这样,预期的字符串实际上就是您所期望的。