DATA-DOG / go-sqlmock

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

How can I make sqlmock not care about the order of arguments? #322

Closed felipe-cg closed 9 months ago

felipe-cg commented 9 months ago

Question

Hello, I have a test for an app using both sqlmock and GORM:

db.ExpectPrepare(regexp.QuoteMeta(`INSERT INTO "table_name").
  ExpectQuery().
  WithArgs(testId, anotherTestId).
  WillReturnRows(sqlmock.NewRows([]string{"test_id", "another_test_id"}).
  AddRow(testId, anotherTestId))

However, when I run my tests, sometimes the query I receive is like this: INSERT INTO "table_name" ("test_id","another_test_id") VALUES ('example','example2') ON CONFLICT DO NOTHING RETURNING "test_id","another_test_id"

And other times, the arguments are swapped like this: INSERT INTO "table_name" ("another_test_id", "test_id") VALUES ('example','example2') ON CONFLICT DO NOTHING RETURNING "test_id","another_test_id"

This inconsistency in the order of arguments causes some tests to fail because sqlmock expects the query arguments in a specific order. I would like to know if there is a way to make sqlmock not care about the order of arguments. Thank you.

JessieAMorris commented 9 months ago

This is something that is not straightforward to implement as order can be very important and it’s not always obvious when it is and isn’t. You may want to check out https://github.com/DATA-DOG/go-sqlmock/issues/207 as this has been discussed before.

It looks like gorm supported named parameters now, so that is probably your best bet. sqlmock had support for them added in https://github.com/DATA-DOG/go-sqlmock/pull/208