unit-testing - 如何编写When a function having the parameters of c *gin.Context 的测试用例

标签 unit-testing go table-driven

我正在用 golang 为我的项目编写 Controller 的测试用例。在 Controller 中有函数名称 SaveProvider() 有参数 c *gin.Context 我不知道如何将 JSON 传递给 c * gin.Context 这个参数以及我如何测试我在 Controller 中使用的函数 谁能告诉我这段代码中的问题是什么。它也称为表驱动测试。

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:                   "harry@gmail.com",
                         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)
        })
     }
}

Controller 中的函数是:-

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))

关于unit-testing - 如何编写When a function having the parameters of c *gin.Context 的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52274333/

相关文章:

javascript - 用于单元测试的 LoopbackJS 注册模型

postgresql - 如何使用 Gorm 连接 PostgreSQL 数据库

design-patterns - 什么是表驱动方法?

compiler-construction - 直接编码与表驱动的词法分析器?

testing - 如何在 Golang 中测试 map 的等价性?

unit-testing - 从 reduceByKey() 调用函数时单元测试期间的导入错误

c# - 单元测试场景——如何测试?

java - IntelliJ - 测试覆盖率。只显示经过测试的类

google-app-engine - 带有光标的Google App Engine数据存储区查询不会迭代所有项

go - 为什么在对象上使用 new() 不会包含在 Go 的内存分析文件中?