lundi 24 juillet 2017

Golang buffer string() not equal string

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.

Aucun commentaire:

Enregistrer un commentaire