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

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

為什么我使用杜松子酒和圍棋的測試沒有通過?

為什么我使用杜松子酒和圍棋的測試沒有通過?

Go
三國紛爭 2022-08-15 19:39:57
我正在嘗試測試我的 API。在這種情況下,我有這個主文件:package mainimport (    "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 mainimport (    "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找不到json密鑰,給出錯誤mykeyKey: 'ID' Error:Field validation for 'ID' failed on the 'required' tag為什么會發生這種情況?我嘗試以不同的方式格式化JSON正文,但我無法使其正常工作
查看完整描述

1 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

Gin 根據請求選擇要使用的綁定。Content-Type

使用 Bind 方法時,Gin 會嘗試根據內容類型標頭推斷綁定程序。如果您確定要綁定的內容,則可以使用 MustBindWith 或 ShouldBindWith。

將代碼更改為:

    req, err := http.NewRequest("POST", "/", body)
    require.Nil(t, err)
    req.Header.Set("Content-Type", "application/json")
    router.ServeHTTP(w, req)


查看完整回答
反對 回復 2022-08-15
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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