简体   繁体   English

SQLMock - Mocking 出链式 DELETE 查询

[英]SQLMock - Mocking out chained DELETE query

I'm currently trying to write a test for a Database query, but stuck on trying to figure out how to mock it out.我目前正在尝试为数据库查询编写测试,但一直试图弄清楚如何模拟它。

I have the following struct (for your reference):我有以下结构(供您参考):

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"`
}

and I have a query that deletes all Users with the same GroupID :我有一个查询删除所有具有相同GroupIDUsers

/*
  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()

Apparently the above query results in the following (taken out from the test error):显然上面的查询结果如下(从测试错误中取出):

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

I can match the query string, but I'm unable to match the argument since it is passed in as a struct.我可以匹配查询字符串,但我无法匹配参数,因为它是作为结构传入的。 Is it possible to mock this call out with go-sqlmock, or do I have to change my query to be able to mock it out?是否可以使用 go-sqlmock 模拟这个调用,或者我是否必须更改我的查询才能模拟它?

yes, this can be mocked with go-sqlmock,是的,这可以用 go-sqlmock 来模拟,

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

I have mocked like this我曾经这样嘲笑过

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM