1

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:

/*
  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?

LDK
  • 11
  • 2

1 Answers1

2

yes, this can be mocked with go-sqlmock,

For this query 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)
}
Venu Hegde
  • 21
  • 6