登录
首页 >  Golang >  Go问答

如何编写当函数具有 c *gin.Context 参数时的测试用例

来源:stackoverflow

时间:2024-04-02 12:42:24 339浏览 收藏

大家好,今天本人给大家带来文章《如何编写当函数具有 c *gin.Context 参数时的测试用例》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在用 golang 为我的项目编写控制器的测试用例。在控制器中,函数名称 saveprovider() 具有参数 c *gin.context ,我不知道如何将 json 传递给 c *gin.context 这个参数以及如何测试控制器中使用的函数任何人都可以告诉我这段代码有什么问题。它也称为表驱动测试。

package controllers

import (
    "bkapiv1/models"
    "fmt"
    "testing"

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

func testsaveprovider(t *testing.t) {
    type args struct {
        c    *gin.context
        json providerprofile
    }
    tests := []struct {
        name string
        args args
        want bool
    }{
        {
            "saveprovider",
            args{
                &gin.context{
                   //how to pass here a json means the below json providerprofile.
                },
                providerprofile{
                     models.user{
                         firstname:                  "harry",
                         lastname:                   "potter",
                         fullname:                   "harry potter",
                         companyname:                "theironnetwork",
                         emailid:                   "[email protected]",
                         password:                   "vadhera123",
                     },
                     models.addressstruct{},
                     models.provider{
                        providercategory: "ic",
                        priority:         1,
                     },
                },
            },
            true,
         },
     }
     for _, tt := range tests {
        t.run(tt.name, func(t *testing.t) {
            saveprovider(tt.args.c)
        })
     }
}

控制器中的功能是:-

func SaveProvider(c *gin.Context){

}

解决方案


有一个 library 适合你想做的事情

handler := func(w http.ResponseWriter, r *http.Request) {
    c := CreateTestContext(w)
    SaveProvider(c)
}

req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
handler(w, req)

resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)

fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
fmt.Println(string(body))

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>