1

我目前正在尝试为数据库查询编写测试,但一直试图弄清楚如何模拟它。

我有以下结构(供您参考):

type User struct {
 ID        uint      `gorm:"column:id;primary_key"`
 CreatedAt time.Time `gorm:"column:created_at"`
 UpdatedAt time.Time `gorm:"column:updated_at"`
 GroupID   uint      `gorm:"column:group_id" sql:"index"`
}

我有一个删除所有Users相同的查询GroupID

/*
  user is an empty User struct
  groupID is an uint declared during test initialization (in this case, set to value 1)
*/
err := d.db.Where("group_id = ?", groupID).Delete(&user).GetErrors()

显然上面的查询结果如下(从测试错误中取出):

call to ExecQuery 'DELETE FROM "users"  WHERE (group_id = $1)' with args [{Name: Ordinal:1 Value:1}]

我可以匹配查询字符串,但我无法匹配参数,因为它是作为结构传入的。是否可以使用 go-sqlmock 模拟这个调用,或者我是否必须更改我的查询才能模拟它?

4

1 回答 1

2

是的,这可以用 go-sqlmock 来模拟,

对于这个查询 err = s.Db.Delete(&user).Error

我曾经这样嘲笑过

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()
mock.ExpectBegin()
mock.ExpectExec(regexp.QuoteMeta("DELETE")).WithArgs(1).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
gormdb, err := gorm.Open("postgres", db)
if err != nil {
    t.Errorf("Failed to open gorm db, got error: %v", err)
}
于 2021-04-02T04:56:22.460 回答