go - 使用 go-mocket 模拟 GORM 数据库不起作用

标签 go mocking go-gorm mockups

我正在尝试使用 go-mocket 来模拟 gorm 数据库,但它无法正常工作。我没有向我的 ClusterExists 函数发送任何模拟数据,因此单元测试无法按预期工作。

在文档中有两种模拟“简单链用法”和“FakeResponse”的方法。我已经尝试了两种方法,但都不起作用。

我的功能:

func ClusterExists(cluster *Cluster, db *gorm.DB) bool {
    c := Cluster{}
    exists := !db.Where("cluster_name = ? AND env_type = ?", cluster.ClusterName, cluster.EnvType).First(&c).RecordNotFound()

    return exists
}

我的测试函数:

func SetupTests() *gorm.DB { 
mocket.Catcher.Register() 
mocket.Catcher.Logging = true
db, err := gorm.Open(mocket.DriverName, "connection_string")
if err != nil {
    log.Fatal(err)
}
db.LogMode(true)
//models.DB = db

return db
}
func TestShouldUpdateStats(t *testing.T){
    t.Run("SIMPLE test", func(t *testing.T){
        DB := SetupTests()
        commonReply := []map[string]interface{}{{"cluster_name":"testname", "env_type":"envtype"}}
        mocket.Catcher.NewMock().WithQuery("SELECT * FROM clusters WHERE").WithReply(commonReply)

        //var declaration
        var testCluster Cluster
        testCluster.ClusterName = "testname"
        testCluster.EnvType = "envtype"

        //assert
        if ClusterExists(&testCluster, DB) {
            t.Errorf("There is a record in the database which already exists:")
        }
    })
}

因为我的 testCluster.ClusterName 和 testCluster.EnvType 与我在数据库中的内容相同,所以我应该收到错误:

t.Errorf("There is a record in the database which already exists:")

但是我从来没有从 ClusterExists 函数收到“真”,所以我不能让测试失败。

你知道我在使用 Go-Mocket 时做错了什么吗?有什么我想念的吗?

亲切的问候!

最佳答案

已修复!

我只使用“WithArgs()”函数匹配了我的查询,它对我有用:)

mocket.Catcher.NewMock().WithArgs("testname","envtypes").WithReply(commonReply)

关于go - 使用 go-mocket 模拟 GORM 数据库不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56984161/

相关文章:

node.js - 拦截IBM的Watson Botkit中间件进行测试

go - 如果数据类型从字符串更改为 bool 数据存储会引发错误

regex - 在 Go 中使用正则表达式拆分字符串

python - 如何模拟在 with 语句中使用的 open (使用 Python 中的 Mock 框架)?

java - 在 Java 中将 WireMock 与 SOAP Web 服务结合使用

go - Golang gorm协会(属于)

types - 为什么Go中有int但没有float?

go - 为什么我们需要 := symbol in golang?

go - 如何为带有动态变量的where子句编写gorm函数

postgresql - 在 Revel 中使用 Gorm 查询表