1

我正在尝试测试我的 API。在这种情况下,我有这个主文件:

package main

import (
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := getRouter()
    r.Run(":8080")
}

func getRouter() *gin.Engine {
    // We create the instance for Gin
    r := gin.Default()

    // Path to the static files. /static is rendered in the HTML and /media is the link to the path to the  images, svg, css.. the static files
    r.StaticFS("/static", http.Dir("../media"))

    // Path to the HTML templates. * is a wildcard
    r.LoadHTMLGlob("*.html")

    r.NoRoute(renderHome)
    // This get executed when the users gets into our website in the home domain ("/")
    r.GET("/", renderHome)
    r.POST("/", getData)
    return r
}

func renderHome(c *gin.Context) {
    c.HTML(http.StatusOK, "my-html.html", gin.H{})
}

func getData(c *gin.Context) {
    formData := &struct {
        ID int `json:"mykey"  binding:"required" `
    }{}
    // Validation (with Gin)
    if err := c.Bind(formData); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        fmt.Print(err)
        return
    }
}

我有这个 main_test 文件

package main

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

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

func TestPost(t *testing.T) {
    // Create Infraestructure
    router := getRouter()
    w := httptest.NewRecorder()
    // Rent Bike
    body := bytes.NewBuffer([]byte("{\"mykey\":1}"))
    req, _ := http.NewRequest("POST", "/", body)
    router.ServeHTTP(w, req)
    // Test data
    assert.Equal(t, http.StatusOK, w.Code)
}

测试失败,因为绑定时,Gin 没有找到mykeyjson key,报错Key: 'ID' Error:Field validation for 'ID' failed on the 'required' tag

为什么会这样?我尝试以不同的方式格式化 JSON 正文,但无法使其正常工作

4

1 回答 1

0

Gin 根据请求选择要使用的绑定Content-Type

当使用 Bind-method 时,Gin 会尝试根据 Content-Type 标头推断 binder。如果您确定要绑定什么,则可以使用 MustBindWith 或 ShouldBindWith。

将您的代码更改为:

    req, err := http.NewRequest("POST", "/", body)
    require.Nil(t, err)
    req.Header.Set("Content-Type", "application/json")
    router.ServeHTTP(w, req)
于 2021-03-19T15:22:13.923 回答