缓冲字符串(Buffer string)与字符串(string)不相等。

huangapple go评论84阅读模式
英文:

Buffer string() not equal string

问题

我试图测试我的HTTP处理程序是否在响应体中返回了正确的值。

这是我的处理程序函数:

func Index(w http.ResponseWriter, r *http.Request){
    message := `{"status": "OK"}`
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")
    if err := json.NewEncoder(w).Encode(message); err != nil {
        panic(err)
    }
}

这是我的测试:

func TestIndex(t *testing.T){

    req, err := http.NewRequest("GET", "/", nil)
    if err != nil {
        t.Fatal(err)
    }

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(Index)

    handler.ServeHTTP(rr, req)

    expected := `{"status": "OK"}`

    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

测试的结果是:

handlers_test.go:244: handler returned unexpected body: got "{\"status\": \"OK\"}"
         want {"status": "OK}

我认为"的转义是由于json编码导致的,但即使我将期望值更改为

expected := `"{\"status\": \"OK\"}"`

它也不起作用,测试的结果是:

handlers_test.go:244: handler returned unexpected body: got "{\"status\": \"OK\"}"
         want "{\"status\": \"OK\"}"

文档中,我找到了关于json编码附加换行符的信息,但即使有这个信息,我也无法使测试正常工作 :-/

提前感谢您的帮助。

英文:

I try to test if my http handler is returning the right values inside the body.

This is my handler function

func Index(w http.ResponseWriter, r *http.Request){
    message := `{"status": "OK"}`
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")
    if err := json.NewEncoder(w).Encode(message); err != nil {
            panic(err)
    }
}

This is my test

func TestIndex(t *testing.T){

    req, err := http.NewRequest("GET", "/", nil)
    if err != nil {
            t.Fatal(err)
    }

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(Index)

    handler.ServeHTTP(rr, req)

    expected := `"{"status": "OK"}"`

    if rr.Body.String() != expected {
    t.Errorf("handler returned unexpected body: got %v want %v",
        rr.Body.String(), expected)
    }
}

The result of the test is:

handlers_test.go:244: handler returned unexpected body: got "{\"status\": \"OK\"}"
	 want {"status": "OK"}

I think the escaping of the " is because of the json Encode, but even if I change the expected to

expected := `"{\"status\": \"OK\"}"`

it does not work, than the result of the test is

handlers_test.go:244: handler returned unexpected body: got "{\"status\": \"OK\"}"
	 want "{\"status\": \"OK\"}"

In the docs I found something that json encode appends a newline character, but I did not manage to get the test working even with that information :-/

In advance, thanks for your help.

答案1

得分: 5

你发送的消息:

message := `{"status": "OK"}`

已经是一个有效的 JSON 文本,你不需要进行任何进一步的 JSON 编码/处理。只需按原样发送即可:

func Index(w http.ResponseWriter, r *http.Request){
    message := `{"status": "OK"}`
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")
    io.WriteString(w, message)
}

还要注意,如果你的响应代码是 http.StatusOK,你不需要显式设置它,因为如果你不设置它,它就是默认值。

然后只需期望以下响应:

expected := `{"status": "OK"}`

解释你原来的代码:

在你的原始代码中,你对一个单独的 string 值进行了 JSON 编组,其内容为 {"status": "OK"}。JSON 编码将此文本引用为有效的 JSON 字符串(用反斜杠引用引号),并放在引号内,还附加了一个换行符。因此,这成为原始字符串:

expected := `"{\"status\": \"OK\"}"
`

使用这个 expected 值,你的测试通过了,但是,你想要的是在本答案的第一部分。

如果你想要使用一个解释的字符串字面量来描述 expected 值,它可能是这样的:

expected := "\"{\\\"status\\\": \\\"OK\\\"}\"\n"
英文:

The message you send:

message := `{"status": "OK"}`

Is already a valid JSON text, you don't need any further JSON encoding / processing on it. Just send it as-is:

func Index(w http.ResponseWriter, r *http.Request){
    message := `{"status": "OK"}`
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")
    io.WriteString(w, message)
}

Also note that if your response code is http.StatusOK, you don't need to set that explicitly, as that is the default if you don't set it.

And then simply expect the following response:

expected := `{"status": "OK"}`

Explaining your original code:

In your original code you JSON-marshaled a single string value, whose content was {"status": "OK"}. JSON encoding will quote this text into a valid JSON string (prefix quotation marks with a backslash), put inside quotes, and also appends a newline character. So this becomes the raw string:

expected := `"{\"status\": \"OK\"}"
`

Using this expected value, your test passes, but again, what you want is in the first part of this answer.

If you want to use an interpreted string literal to describe the expected value, this is how it could look like:

expected := "\"{\\\"status\\\": \\\"OK\\\"}\"\n"

答案2

得分: 0

这是翻译好的内容:

换行符是问题所在。我通过添加 strings.TrimRight 并将其从字符串中删除来解决了它。

if strings.TrimRight(rr.Body.String(), "\n") != expected {
    t.Errorf("handler returned unexpected body: got %v want %v",
        rr.Body.String(), expected)
    }
英文:

The linebreak was the problem. I managed to solve it with adding strings.TrimRight and cut if right off the string.

if strings.TrimRight(rr.Body.String(), "\n") != expected {
    t.Errorf("handler returned unexpected body: got %v want %v",
        rr.Body.String(), expected)
    }

huangapple
  • 本文由 发表于 2017年7月24日 16:02:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/45275185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定