使用Echo测试POST请求(预期与实际输出)

时间:2018-11-05 23:00:21

标签: json go post go-echo

我对Go语言很陌生,所以,很抱歉,这是一个愚蠢的问题。

我最近一直在尝试使用Echo的一些API。我正在尝试测试Go echo的route(POST)处理程序,该处理程序获取json并将其放入数组中。贝娄是处理程序 main.go 和测试 test_main.go

的代码

main.go

type Houses struct {
Name    string `json:"name,ommitempty"`
Address string `json:"address,omitempty"`
}

var houses []Houses

func newHouse(c echo.Context) error {
    m := echo.Map{}
    if err := c.Bind(&m); err != nil {
        return err
    }
    dv := Houses{
        Name:    m["name"].(string),
        Address: m["address"].(string),
    }
    houses = append(houses, dv)
    js, _ := json.Marshal(houses)
    fmt.Println(fmt.Sprintf("%s", js))

    return c.JSON(http.StatusOK, string(js))
}

test_main.go

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "github.com/labstack/echo"
    "github.com/stretchr/testify/assert"
)

var userJSON = `{"name":"Jhon Doe","address":"High St."}`

func TestModel(t *testing.T) {
    url := "/new_house"
    e := echo.New()
    req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(userJSON))
    req.Header.Set("Content-Type", "application/json")
    if err != nil {
        t.Errorf("The request could not be created because of: %v", err)
    }
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)
    // c.SetPath("/new_house")
    // c.JSON(http.StatusOK, Devices{"Jhon Doe", "Middle Way"})

    res := rec.Result()
    defer res.Body.Close()

    if assert.NoError(t, newHouse(c)) {
        assert.Equal(t, http.StatusOK, rec.Code)
        assert.Equal(t, "["+userJSON+"]", rec.Body.String())
    }
}

即使通过curl调用处理程序也可以正常工作,但测试失败并显示以下错误。

[{"name":"Jhon Doe","address":"High St."}]
--- FAIL: TestModel (0.00s)
    /home/gaidaros/Code/echo-badger/models/model_test.go:34: 
            Error Trace:    model_test.go:34
            Error:          Not equal: 
                            expected: "[{\"name\":\"Jhon Doe\",\"address\":\"High St.\"}]"
                            actual  : "\"[{\\\"name\\\":\\\"Jhon Doe\\\",\\\"address\\\":\\\"High St.\\\"}]\""

                            Diff:
                            --- Expected
                            +++ Actual
                            @@ -1 +1 @@
                            -[{"name":"Jhon Doe","address":"High St."}]
                            +"[{\"name\":\"Jhon Doe\",\"address\":\"High St.\"}]"
            Test:           TestModel
FAIL
exit status 1

经过几天的努力,我不知道如何使实际输出与期望的相符,所以我在这里发布,希望能够克服这个障碍。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您要在json.Marshal上调用[]Houses,将其封送为JSON字符串,然后您要使用JSON字符串来调用echo.Context.JSON,而内部则调用json.Marshal。双重编组会导致逃逸。参见示例。 (为简便起见,省略了错误检查)

https://play.golang.org/p/nYvHS4huy0M

h := &Houses{"Jhon Doe", "High St."}
d, _ := json.Marshal(h)

// double marshal bad
d, _ = json.Marshal(string(d))

fmt.Println(string(d))
// prints "{\"name\":\"Jhon Doe\",\"address\":\"High St.\"}"

您的解决方案是将切片传递给您的c.JSON调用。附带说明,您应该能够将结构传递给c.Bind,而不是使用带有类型断言的映射。