我正在用 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/