json - 使用 Echo 测试 POST 请求(预期与实际输出)
问题描述
我是 Go 的新手,所以,如果这是一个愚蠢的问题,我很抱歉。
我最近一直在尝试一些带有 Echo 的 API。我正在尝试测试获取 json 并将其放入数组的 Go echo 的 route(POST) 处理程序。Bellow 是处理程序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
经过几天的努力,我无法弄清楚如何使实际输出与预期相匹配,所以我在这里发帖希望能克服这个障碍。任何帮助表示赞赏!
解决方案
您正在调用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
而不是使用带有类型断言的映射。
推荐阅读
- php - 我对 MySQL 中的“UPDATE”命令有疑问
- python - 返回一个由函数调用的 2 个参数组合的新元组
- java - 一个 NetBeans 项目可以加载 .dll,但另一个抛出“无法在 IA 32 位平台上加载 AMD 64 位 .dll”
- gcc - makefile: 没有规则来制作目标'%.o'
- swift - 如何读取保存为 hex.txt 的文本文件,它在 Swift 中具有十六进制值?
- python - 为每个重复的 N 行创建一行
- c# - cshtml onclick 事件中的按钮从 cshtml.cs 读取函数
- angular - 如何在 Angular 6 中禁用 simplemde?
- c# - 来自 NPC 的光线投射
- node.js - AWS Lambda/Chromium - 评估期间定义的函数“未定义”