为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
扬帆大鱼 2023-05-08 14:35:31
我是 Go 的新手,所以,如果这是一个愚蠢的问题,我很抱歉。我最近一直在尝试使用 Echo 的一些 API。我正在尝试测试获取 json 并将其放入数组中的 Go echo 的路由(POST)处理程序。下面是处理程序main.go和测试test_main.go的代码main.gotype Houses struct {Name    string `json:"name,ommitempty"`Address string `json:"address,omitempty"`}var houses []Housesfunc 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.goimport (    "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 调用处理程序正常工作,测试也会失败并显示如下错误。经过几天的努力,我无法弄清楚如何使实际输出符合预期,所以我在这里发帖希望能克服这个障碍。任何帮助表示赞赏!
查看完整描述

1 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

您正在调用json.Marshal[]Houses它将其编组为 JSON 字符串,然后您echo.Context.JSON使用 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而不是使用带有类型断言的映射。


查看完整回答
反对 回复 2023-05-08
  • 1 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信