I want to test a DB query in go. For that I try to use the sqlmock library. Sadly I don't find a solution to this
My test is
t.Run("call database", func(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
var picArray []string
technique := "ballpoint"
mock.ExpectBegin()
mock.ExpectQuery("SELECT * FROM pictures")
wanted := picture.Picture{"hurr", "durr", 2020, "hurrdurr"}
got := GetPicture(db, technique)
if got != wanted {
t.Errorf("got %q, wanted %q", got, picArray)
}
})
}
And my code looks like this
func GetPicture(db *sql.DB, style string) picture.Picture {
rows, err := db.Query("SELECT * FROM pictures")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var (
name string
technique string
year int
fileName string
)
pic := picture.Picture{}
for rows.Next() {
err := rows.Scan(&name, &technique, &year, &fileName)
if err != nil {
log.Fatal(err)
}
log.Println(name, technique, year, fileName)
pic.Name = name
pic.Technique = technique
pic.Year = year
pic.FileName = fileName
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return pic
}
If I run the test, I get the following error
2020/12/07 20:23:46 call to Query 'SELECT * FROM pictures' with args [], was not expected, next expectation is: ExpectedBegin => expecting database transaction Begin
exit status 1
How can I check, if the query is called?
Ok, so I had to call db.Begin()
.