I am writing tests with sqlmock
in go
. I have a list of rows (e.g. myRows
) and two different SELECT
statements which I want to use myRows
as WillReturnRows
argument for both of them:
myRows := sqlmock.NewRows([]string{"my_column"}).AddRow(1)
mock.ExpectQuery(firstQuery).WillReturnRows(myRows)
mock.ExpectQuery(secondQuery).WillReturnRows(myRows)
When I use it in the first WillReturnRows
, it returns 1
as result. But in the second usage, no rows is returned as result; I mean empty rows returns. I printed out the myRows
before and after first call in order to check if it's been consumed or not; the object had no change:
Rows Before: &{[my_column] [[1]] 0 map[] <nil>}
Rows After: &{[my_column] [[1]] 0 map[] <nil>}
Edit 1:
I used following code and it works; it means both queries return 1
:
myRows1 := sqlmock.NewRows([]string{"my_column"}).AddRow(1)
myRows2 := sqlmock.NewRows([]string{"my_column"}).AddRow(1)
mock.ExpectQuery(firstQuery).WillReturnRows(myRows1)
mock.ExpectQuery(secondQuery).WillReturnRows(myRows2)
A quick glance at the source suggests that the instance can't be re-used, you will have to create as many instances of sqlmock.Rows
as the select queries that you expect. Each time your code calls Next
on the sql.Rows
instance, whether directly or indirectly, the position in sqlmock.Rows
gets incremented and so... the second query has no more rows to scan.