登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-05 08:18:34 400浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何正确测试Gin-gonic控制器?》,涉及到,有需要的可以收藏一下

问题内容

我正在通过使用 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 模拟存储库)

例如 如果我有这样的路线 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          = "[email protected]"
        password       = "P@ssw0rd"
        hashedPassword = "$2y$12$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) 并调用内部测试用例快乐用例

staffmock.expect().createstaff(gomock.any(), gomock.any()).return(&createdstaffentity, nil) 这是一个模拟函数,它将按照我想要的方式返回值(同样,您应该阅读更多有关 gomock 的内容,您会明白我想说的)

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>