如何正确测试 Gin-gonic 控制器?

How to test Gin-gonic controller properly?

我正在通过使用 Gin-gonic 作为 http 处理程序框架来学习 golang。我有一个端点控制器,它使用我自己的 Email 结构进行操作,如下所示:

func EmailUserVerification(c *gin.Context) {
    var input validators.EmailUserVerificationValidator
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    email := models.Email{
        To:       input.To,
        Subject:  input.Subject,
        Template: "user_verification.html",
        TemplateData: notices.EmailUserVerificationTemplateData{
            Name:             input.Name,
            VerificationLink: input.VerificationLink,
        },
        Sender: models.NewEmailSMTPSender(input.From),
    }

    if err := email.Deliver(); err != nil {
        panic(err)
    }
    c.JSON(http.StatusCreated, nil)
}

Struct Email 已经测试过了,不过我不知道如何正确测试这个方法。 Email 结构应该如何在这里被模拟?

我将处理程序注册为 gin-gonic 文档说:

router.POST("/emails/users/verify", controllers.EmailUserVerification)

也许我可以在处理程序中注入一个电子邮件接口?如果是这样,我该如何注入?

提前致谢^^

您可以通过创建测试文件来测试它,其中包含测试函数并模拟其他调用函数。 对我来说,我使用 testify/mock 来模拟 func(为了进一步解释,你应该先从其他网站阅读,比如 medium 和 GitHub mock repo)

例如 如果我有这样的路线 v1.POST("/operators/staffs", handler.CreateStaff) 并具有内部调用 func handler.OperatorStaffUseCase.CreateStaff

的函数 handler.CreateStaff

我将创建如下所示的文件 create_staff_test.go

package operator_staff

import (
    "encoding/json"
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/golang/mock/gomock"
    jsoniter "github.com/json-iterator/go"
    "github.com/pkg/errors"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
    "net/http"
    "net/http/httptest"
    "onboarding-service/app/entities"
    staffUseCaseMock "onboarding-service/app/mocks/usecases"
    "strings"
    "testing"
)

func TestStaffHandler_CreateStaff(t *testing.T) {
    var (
        invitationId   = "3da465a6-be13-405e-a653-c68adf59f2be"
        firstName      = "Tom"
        lastName       = "Sudchai"
        roleId         = uint(1)
        roleName       = "role"
        operatorCode   = "velo"
        email          = "toms@gmail.com"
        password       = "P@ssw0rd"
        hashedPassword = "y$S0Gbs0Qm5rJGibfFBTARa.6ap9OBuXYbYJ.deCzsOo4uQNJR1KbJO"
    )

    gin.SetMode(gin.TestMode)
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()
    staffMock := staffUseCaseMock.NewMockOperatorStaffUseCase(ctrl)

    executeWithContext := func(mockUseCase *staffUseCaseMock.MockOperatorStaffUseCase, jsonRequestBody []byte, operatorCode string) *httptest.ResponseRecorder {
        response := httptest.NewRecorder()
        context, ginEngine := gin.CreateTestContext(response)

        requestUrl := "/v1/operators/staffs"
        httpRequest, _ := http.NewRequest("POST", requestUrl, strings.NewReader(string(jsonRequestBody)))

        NewEndpointHTTPHandler(ginEngine, mockUseCase)
        ginEngine.ServeHTTP(response, httpRequest)
        return response
    }

    createdStaffEntity := entities.OperatorStaff{
        ID:        roleId,
        FirstName: firstName,
        LastName:  lastName,
        Email:     email,
        Password:  hashedPassword,
        Operators: []entities.StaffOperator{{
            OperatorCode: operatorCode, RoleID: roleId,
        }},
    }

    t.Run("Happy", func(t *testing.T) {
        jsonRequestBody, _ := json.Marshal(createStaffFromInviteRequestJSON{
            InvitationId:    invitationId,
            FirstName:       firstName,
            LastName:        lastName,
            Password:        password,
            ConfirmPassword: password,
        })
    
        staffMock.EXPECT().CreateStaff(gomock.Any(), gomock.Any()).Return(&createdStaffEntity, nil)

        res := executeWithContext(staffMock, jsonRequestBody, operatorCode)
        assert.Equal(t, http.StatusOK, res.Code)
    })
}

你会看到 最初测试时的第一个模拟功能 staffMock := staffUseCaseMock.NewMockOperatorStaffUseCase(ctrl) 并调用内部测试用例 happy case

staffMock.EXPECT().CreateStaff(gomock.Any(), gomock.Any()).Return(&createdStaffEntity, nil) 这是模拟函数,它将 return 值按我想要的(同样,你应该阅读更多关于 gomock 的信息,你会明白我想说的)

或者为了学习测试的简单方法,请阅读本教程 https://github.com/JacobSNGoodwin/memrizr