How to stub database connection with GORM
This article is a note when I was looking for how to stub database connection with GORM.
At first, I found go-sqlmock. It stubs database connection. I thought that it’s easy to make connection stub.
go-sqlmock makes stub connection & return it.
//db is sql.DB https://golang.org/pkg/database/sql/
db, mock, err := sqlmock.New()
So, I tried to set db to GORM. But GORM hides db field of their DB struct.
I looked into GORM & go-sqlmock, and I understood following.
So the code is like this.
var db *gorm.DB
_, mock, err := sqlmock.NewWithDSN("sqlmock_db_0")
if err != nil {
panic("Got an unexpected error.")
}
db, err = gorm.Open("sqlmock", "sqlmock_db_0")
if err != nil {
panic("Got an unexpected error.")
}
defer db.Close()
rs := sqlmock.NewRows([]string{"count"}).FromCSVString("1")
mock.ExpectQuery(`SELECT count.* FROM "whitelist" WHERE.*$`).
WithArgs(12345).
WillReturnRows(rs)
....
....