亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 235 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號