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!