I have a Gorm delete with the returning result:
expirationDate := time.Now().UTC().Add(-(48 * time.hour))
var deletedUsers Users
res := gormDB.WithContext(ctx).
Table("my_users").
Clauses(clause.Returning{Columns: []clause.Column{{Name: "email"}}}).
Where("created_at < ?", expirationDate).
Delete(&deletedUsers)
Now the test with clauses always fails. e.g. :
sqlMock.ExpectExec(`DELETE`)
.WithArgs(expirationDate)
.WillReturnResult(sqlmock.NewResult(1, 1))
Receiving error:
"call to Query 'DELETE FROM "my_users" WHERE created_at < $1 RETURNING "email"' with args [{Name: Ordinal:1 Value:2023-01-18 06:15:34.694274 +0000 UTC}], was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which:\n - matches sql: 'DELETE'\n - is with arguments:\n 0 - 2023-01-18 06:15:34.694274 +0000 UTC\n - should return Result having:\n LastInsertId: 1\n RowsAffected: 1"
I tried many other sqlMock expectations, but they have a similar issue. Also, we don't have a return value in ExpectExec, only in ExpectQuery... Any chance someone has to test the Gorm query with the Clauses?
I was able to successfully manage what you need. First, let me share the files I wrote, and then I'll walk you through all of the relevant changes. The files are
repo.go
for production andrepo_test.go
for the test code.repo.go
As you didn't provide the full file I tried to guess what was missing.
repo_test.go
Here, there are more changes that it's worth mentioning:
AnyTime
as per the documentation (you can see the link in the comment).db
,mock
, andgormDb
but I think it should be more or less the same.ExpectExec
toExpectQuery
as we'll have back a result set as specified by theClauses
method in yourrepo.go
file.ExpectQuery
within anExpectBegin
and anExpectCommit
.?
or$1
. However, in the test code, you can only use the?
otherwise it won't match the expectations.Hope to help a little bit, otherwise, let me know!