Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何对Go-Gin处理程序函数进行单元测试?_Unit Testing_Go_Integration Testing_Go Gin - Fatal编程技术网

Unit testing 如何对Go-Gin处理程序函数进行单元测试?

Unit testing 如何对Go-Gin处理程序函数进行单元测试?,unit-testing,go,integration-testing,go-gin,Unit Testing,Go,Integration Testing,Go Gin,我有一个像这样的控制器功能 func GetMaterialByFilter(c *gin.Context) { queryParam := weldprogs.QueryParam{} c.BindQuery(&queryParam) materialByFilter, getErr := services.WeldprogService.GetMaterialByFilter(&queryParam) if getErr != nil {

我有一个像这样的控制器功能

func GetMaterialByFilter(c *gin.Context) {

    queryParam := weldprogs.QueryParam{}
    c.BindQuery(&queryParam)
    materialByFilter, getErr := services.WeldprogService.GetMaterialByFilter(&queryParam)
    if getErr != nil {
        //TODO : Handle user creation error
        c.JSON(getErr.Status, getErr)
        return
    }
    c.JSON(http.StatusOK, materialByFilter)

}
QueryParam结构如下

type QueryParam struct {
    Basematgroup_id []string `form:"basematgroup_id"`
    License_id      []string `form:"license_id"`
    Diameter_id     []string `form:"diameter_id"`
    Gasgroup_id     []string `form:"gasgroup_id"`
    Wiregroup_id    []string `form:"wiregroup_id"`
    Wiremat_id      []string `form:"wiremat_id"`
}
func TestGetMaterialByFilter(t *testing.T) {
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)
    GetMaterialByFilter(c)
    assert.Equal(t, 200, w.Code) 

    var got gin.H
    err := json.Unmarshal(w.Body.Bytes(), &got)
    if err != nil {
        t.Fatal(err)
    }
    fmt.Println(got)
    assert.Equal(t, got, got) 
}
我的测试函数是这样的

type QueryParam struct {
    Basematgroup_id []string `form:"basematgroup_id"`
    License_id      []string `form:"license_id"`
    Diameter_id     []string `form:"diameter_id"`
    Gasgroup_id     []string `form:"gasgroup_id"`
    Wiregroup_id    []string `form:"wiregroup_id"`
    Wiremat_id      []string `form:"wiremat_id"`
}
func TestGetMaterialByFilter(t *testing.T) {
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)
    GetMaterialByFilter(c)
    assert.Equal(t, 200, w.Code) 

    var got gin.H
    err := json.Unmarshal(w.Body.Bytes(), &got)
    if err != nil {
        t.Fatal(err)
    }
    fmt.Println(got)
    assert.Equal(t, got, got) 
}
在运行这个测试时,它给了我以下错误

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x97f626]

但是当我注释掉控制器函数中的c.BindQuery()行时,它成功地运行了测试函数。我做错了什么?我可以模拟c.BindQuery函数吗?

要测试涉及HTTP请求的操作,必须实际初始化
*HTTP.request
,并将其设置为Gin上下文。要专门测试
c.BindQuery
,只需正确初始化请求的
URL
URL.RawQuery

func mockGin() (*gin.Context, *httptest.ResponseRecorder) {
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)

    // test request, must instantiate a request first
    req := &http.Request{
        URL:    &url.URL{},
        Header: make(http.Header), // if you need to test headers
    }
    // example: req.Header.Add("Accept", "application/json")

    // request query
    testQuery := weldprogs.QueryParam{/* init fields */}

    q := req.URL.Query()
    for _, s := range testQuery.Basematgroup_id {
        q.Add("basematgroup_id", s)
    }
    // ... repeat for other fields as needed

    // must set this, since under the hood c.BindQuery calls
    // `req.URL.Query()`, which calls `ParseQuery(u.RawQuery)`
    req.URL.RawQuery = q.Encode()
    
    // finally set the request to the gin context
    c.Request = req

    return c, w
}

无法按原样测试服务调用
services.WeldprogService.GetMaterialByFilter(&queryParam)
。为了可测试,它必须(理想情况下)是一个接口,并以某种方式作为处理程序的依赖项注入

假设它已经是一个接口,要使其可注入,您可以要求它作为处理程序参数,但这会迫使您更改处理程序的签名,或者将其设置为Gin上下文值:

func GetMaterialByFilter(c *gin.Context) {
    //...
    weldprogService := mustGetService(c)
    materialByFilter, getErr := weldprogService.GetMaterialByFilter(&queryParam)
    // ...
}

func mustGetService(c *gin.Context) services.WeldprogService {
    svc, exists := c.Get("svc_context_key")
    if !exists {
        panic("service was not set")
    }
    return svc.(services.WeldprogService)
}
然后,您可以在单元测试中模拟它:

type mockSvc struct {
}

// have 'mockSvc' implement the interface 

func TestGetMaterialByFilter(t *testing.T) {
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)

    // now you can set mockSvc into the test context
    c.Set("svc_context_key", &mockSvc{})

    GetMaterialByFilter(c)
    // ... 
}

BindQuery
尝试umarshal
*http.Request
的查询参数。在测试中,您忘记初始化该请求并用查询参数填充它。您可以找到如何在测试中使用
CreateTestContext
的示例。