DATA-DOG / go-sqlmock

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

How to mock multiple query cases #338

Closed huanggze closed 1 month ago

huanggze commented 1 month ago

Question

Hi, how can i do code like this:

sqlSelect := mock.ExpectQuery("SELECT (.+) FROM products WHERE (.+)")

sqlSelect.WithArgs("1").WillReturnRows(sqlmock.NewRows(columns).FromCSVString("1,USD,100"))
sqlSelect.WithArgs("2").WillReturnRows(emptyRows)
sqlSelect.WithArgs("3").WillReturnRows(sqlmock.NewRows(columns).FromCSVString("3,USD,200"))

I'd like to mock multip query cases in one mock. It seems not possible, since ExpectQuery only accept WithArgs once.

thanks

diegommm commented 1 month ago

Hi @huanggze! mock.ExpectQuery returns an expectation for a single call to either Query or QueryRow (see here). To mock multiple calls, call mock.ExpectQuery for each one of them. In your case, you can define a constant or a variable with your query regexp and then reuse it in each call to mock.ExpectQuery.