0

我正在尝试使用 go-mocket 来模拟 gorm db,但它不能正常工作。我没有向我的 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("数据库中有一条已经存在的记录:")

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

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

亲切的问候!

4

1 回答 1

0

固定的!

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

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

于 2019-07-12T10:38:28.240 回答