我想测试一个数据库查询。为此,我尝试使用 sqlmock 库。可悲的是我没有找到解决方案我的测试是 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) } })}我的代码看起来像这样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}如果我运行测试,我会收到以下错误2020/12/07 20:23:46 call to Query 'SELECT * FROM pictures' with args [], was not expected, next expectation is: ExpectedBegin => expecting database transaction Beginexit status 1如果调用了查询,我该如何检查?
- 1 回答
- 0 关注
- 174 浏览
添加回答
举报
0/150
提交
取消