我正在尝试使用 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/