使用curl进行测试是可行的,但与"httptest.NewRequest"相同的POST失败



使用这个curl命令,我可以在后台创建部件。请求已成功验证。

curl -XPOST -H"Content-Type: application/json" localhost:8080/v1/parts/ -d'{"custom_id":"test"}' -D -

但另一方面,如果我试图在测试中重新创建该请求,那么它就不被认为是有效的请求:

错误消息:";无法将请求绑定到部件";

我不明白为什么卷曲有效时测试失败了。有人能发现错误吗?

处理程序/部件测试.go

func TestCreatePart(t *testing.T) {
// Setup
e := echo.New()
reqBody := strings.NewReader(`{"custom_id": "custom"}`)
req := httptest.NewRequest(http.MethodPost, "/parts", reqBody)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
if assert.NoError(t, CreatePart(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "userJSON", rec.Body.String())
}
}

处理程序/part.go

func CreatePart(c echo.Context) error {
resp := renderings.PartResponse{}
pr := new(bindings.CreatePartRequest)
if err := c.Bind(pr); err != nil {
resp.Success = false
resp.Message = "Unable to bind request to parts"
return c.JSON(http.StatusBadRequest, resp)
}
if err := pr.Validate(c); err != nil {
resp.Success = false
resp.Message = err.Error()
return c.JSON(http.StatusBadRequest, resp)
}

内部/绑定/部件。go

package bindings
import (
"fmt"
"github.com/labstack/echo"
)
type CreatePartRequest struct {
CustomID string `json:"custom_id" xml:"custom_id" form:"custom_id" query:"custom_id"`
}
func (pr CreatePartRequest) Validate(c echo.Context) error {
errs := new(RequestErrors)
fmt.Println("pr: ", pr.CustomID)
if pr.CustomID == "" {
errs.Append(ErrCustomIDEmpty)
}
if errs.Len() == 0 {
return nil
}
return errs
}

尝试添加req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON),它可能与内容类型标头有关。

最新更新