登录
首页 >  Golang >  Go问答

进行单元测试使用 Gin-Gonic

来源:stackoverflow

时间:2024-02-29 11:03:25 213浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《进行单元测试使用 Gin-Gonic》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我的项目分为三个主要组件:控制器、服务和模型。当通过 uri 查询路由时,控制器被调用,然后控制器调用服务与模型交互,模型再通过 gorm 与数据库交互。

我正在尝试为控制器编写单元测试,但我很难理解如何在模拟杜松子酒层时正确模拟服务层。我可以得到一个模拟的杜松子酒上下文,但我无法在我的控制器方法中模拟服务层。下面是我的代码:

resourcecontroller.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 分配给 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.
}

到这里,我们也就讲完了《进行单元测试使用 Gin-Gonic》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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