Home >Backend Development >Golang >How to Effectively Unit Test Gin Handler Functions with Mocks?

How to Effectively Unit Test Gin Handler Functions with Mocks?

DDD
DDDOriginal
2024-12-17 20:31:12827browse

How to Effectively Unit Test Gin Handler Functions with Mocks?

Mocks to Unit Test Gin Handler Functions

Testing c.BindQuery Functionality

To test operations involving the HTTP request in Gin, initialize an *http.Request and set it to the Gin context. Specifically for testing c.BindQuery, initialize the request's URL and URL.RawQuery:

import (
    "net/http/httptest"

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

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

    // Test request
    req := &http.Request{
        URL: &url.URL{},
        Header: make(http.Header),
    }

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

    q := req.URL.Query()
    for _, s := range testQuery.Basematgroup_id {
        q.Add("basematgroup_id", s)
    }

    // Set URL.RawQuery
    req.URL.RawQuery = q.Encode()

    // Set request to Gin context
    c.Request = req

    return c, w
}

Mocking JSON Binding

Refer to this resource for guidance on mocking JSON binding.

Testing Services

Services like services.WeldprogService.GetMaterialByFilter(&queryParam) cannot be tested as is. To make them testable:

  • Convert them into interfaces.
  • Inject them as dependencies into the handler.
  • Set them as Gin context values.

Interface and Context Value Approach:

type services interface {
    GetMaterialByFilter(*weldprogs.QueryParam) (*weldprogs.MaterialByFilter, error)
}

func mockWeldprogService(service services) {
    return func(c *gin.Context) {
        c.Set("svc_context_key", service)
    }
}

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

    c.Use(mockWeldprogService(&mockSvc{}))

    GetMaterialByFilter(c)

    // ...
}

The above is the detailed content of How to Effectively Unit Test Gin Handler Functions with Mocks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn