DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
5.95k stars 404 forks source link

How to mock an update with returning #328

Closed agustin-del-pino closed 1 month ago

agustin-del-pino commented 7 months ago

Hi!,

I've the following update:

ret := r.db.Exec(regexp.QuoteMeta("UPDATE $1 SET Counter = Counter + $2 RETURNING Counter + 1"), "COUTERS", n)
var c int
ret.Scan(&c)

The test has:

m.ExpectQuery(
        regexp.QuoteMeta(
            `UPDATE $1 SET Counter = Counter + $2 RETURNING Counter + 1`,
        )).WithArgs("COUNTERS", 3).
        WillReturnRows(sqlmock.NewRows([]string{""}).AddRow(1)

When I run the test I got this error.

call to ExecQuery 'UPDATE \$1 SET Counter = Counter + \$2 RETURNING Counter + 1)' with args [{Name: Ordinal:1 Value:COUNTERS} {Name: Ordinal:2 Value:3}], was not expected, next expectation is: ExpectedQuery => expecting Query, QueryContext or QueryRow which:

I understand that error is because I'm using Exec. But I don't know how to return the value I need with the Exec mock.

Is there any method for return a value with Exec mock?.

IvoGoman commented 7 months ago

When using ExpecExec(..) it is possible to set expectations for the result by calling .WillReturnResult(..) Have a look at https://github.com/DATA-DOG/go-sqlmock#tests-with-sqlmock for a working example.

diegommm commented 1 month ago

Hi @agustin-del-pino! It appears you are calling method Exec but expecting a Query instead, which may be your sqlmock issue. But more thoroughly, I think you have a couple of mistakes in your code, some may be due to copy-pasting, but it makes much harder to help you if you don't provide working code (it's fine to redact/change some parts, but make sure at it at least compiles):

To answer the question in the title (How to mock an update with returning): you should either first use Query/QueryRow/QueryContext/QueryRowContext in your runtime code, then your test use the single ExpectQuery method.