gpt4 book ai didi

unit-testing - 使用 Gin-Gonic 进行单元测试

转载 作者:行者123 更新时间:2023-11-28 21:35:34 27 4
gpt4 key购买 nike

我的项目分为三个主要部分: Controller 、服务和模型。当通过 URI 查询路由时,将调用 Controller ,然后调用服务与模型交互,然后模型通过 gorm 与数据库交互。

我正在尝试为 Controller 编写单元测试,但我很难理解如何在模拟 gin 层时正确地模拟服务层。我可以获得一个模拟的 Gin 上下文,但我无法在我的 Controller 方法中模拟服务层。下面是我的代码:

资源 Controller .go

package controllers

import (
"MyApi/models"
"MyApi/services"
"github.com/gin-gonic/gin"
"net/http"
)

func GetResourceById(c *gin.Context) {
id := c.Param("id")
resource, err := services.GetResourceById(id)

if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest, "message": err})
return
} else if resource.ID == 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "message": "Resource with id:"+id+" does not exist"})
return
}

c.JSON(http.StatusOK, gin.H{
"id": resource.ID,
"data1": resource.Data1,
"data2": resource.Data2,
})
}

我想测试 c.JSON 是否返回正确的 http 状态和其他数据。我需要模拟 id 变量、err 变量和 c.JSON 函数,但是当我尝试设置 c. JSON 函数在测试我的新函数时,我收到一条错误消息,提示 Cannot assign to c.JSON。以下是我编写测试的尝试:

resourceController_test.go

package controllers

import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http/httptest"
"testing"
)

func TestGetResourceById(t *testing.T) {
var status int
var body interface{}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.JSON = func(stat int, object interface{}) {
status = stat
body = object
}
GetResourceById(c)
assert.Equal(t, 4, 4)
}

如何正确编写单元测试来测试 c.JSON 是否返回正确的值?

最佳答案

您不能在 Go 中修改类型的方法。它由在编译时定义类型的包定义和不可变。这是 Go 的设计决定。不要这样做。

您已经使用 httptest.NewRecorder() 作为 gin.Context.ResponseWriter 的模拟,它将记录写入响应的内容,包括 c.JSON 调用。但是,您需要保留对 httptest.ReponseRecorder 的引用,稍后再进行检查。请注意,您只有一个编码的 JSON,因此您需要对其进行解码以检查内容(因为 Go 映射和 JSON 对象的顺序无关紧要,检查编码字符串的相等性很容易出错)。

例如,

func TestGetResourceById(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
GetResourceById(c)
assert.Equal(t, 200, w.Code) // or what value you need it to be

var got gin.H
err := json.Unmarshal(w.Body.Bytes(), &got)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, want, got) // want is a gin.H that contains the wanted map.
}

关于unit-testing - 使用 Gin-Gonic 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com