douyun8674 2019-07-11 07:50
浏览 206

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

I am trying to mock a gorm db by using go-mocket but it doesn't work as it should. I am not sending any mock-data to my ClusterExists function so that the unit test doesn't work as I expect.

In the documentation there're two ways of mocking "Simple chain usage" and "FakeResponse". I've tried with both ways and It doesn't work neither.

My function:

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
}

My Tests functions:

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:")
        }
    })
}

As my testCluster.ClusterName and testCluster.EnvType are the same content as I have in my database, I should receive the error:

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

But I never receive a 'true' from the ClusterExists function so, I can't make to fail the test.

Do yo know what I am doing wrong with Go-Mocket? Is there something that I am missing?

Kind Regards!

  • 写回答

1条回答 默认 最新

  • douren2395 2019-07-12 10:38
    关注

    Fixed!

    I have matched my query by using only 'WithArgs()' function and it works for me :)

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

    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思