Closed LucasMHI closed 5 months ago
@LucasMHI have you got any solution? as I am facing same.
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `bar` WHERE id = ?")).
WithArgs(2).
WillReturnRows(barRows)
change to:
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `bar` WHERE `bar`.`id` = ?"")).
WithArgs(2).
WillReturnRows(barRows)
maybe a bit late, but for it to work your test should look like this.
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `bar` WHERE id = ?")).
WithArgs(2).
WillReturnRows(barRows)
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `foo` WHERE id = ?")).
WithArgs(1).
WillReturnRows(fooRows)
change to
mock.ExpectQuery("SELECT(.*)").
WithArgs(1).
WillReturnRows(fooRows)
mock.ExpectQuery("SELECT(.*)").
WithArgs(2).
WillReturnRows(barRows)
I hope it will help a next reader
db. Where("id = ?", input.ID). Preload("Bar"). Find(&foo)
it does not work
这个问题有几个关键点:
总的来说就是sql语句完全正确,且mock的数据关联关系完全正确。
Hi @LucasMHI! Please, consider that GORM is a separate library that is unrelated to sqlmock
, and it has a completely different approach. GORM can help you do fast prototyping and generate a lot of SQL code for you, but you lose some control on what SQL code is being run and how. This means that GORM adds an abstraction layer that you have to account for. Consider the following:
database/sql
instead and building the SQL code so that the code you run is predictable and deterministic.Thank you!
Request
Hello! I'm currently working on a project using GORM for database interaction and have been having difficulty finding any examples for go-sqlmock that involve using the
Preload
method used by GORM, which is used loading associated data, https://gorm.io/docs/preload.htmlFor example, given a database model like this: (keep in mind this has not been 100% tested)
What is wrong with this test function:
I have tried this with a similar situation with preloading and such, however the
SELECT * FROM 'bar'
query is never executed, presumably because I'm missing something in regards to GORM's Preloading statement.Does anyone have suggestions?
Thanks!!