0

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)
Zeinab Abbasimazar
  • 9,835
  • 23
  • 82
  • 131
  • You're assuming that the problem is with re-using an `*sqlmock.Rows` instance... does that mean that you've tried creating two `*sqlmock.Rows` instances and you've used them separately for the separate queries and in that test everything was working as it is supposed to? – mkopriva Feb 02 '20 at 09:11
  • @mkopriva, yes. This is exactly what happened. I will edit my question. – Zeinab Abbasimazar Feb 02 '20 at 09:20
  • 1
    A quick glance at the [source](https://github.com/DATA-DOG/go-sqlmock/blob/master/rows.go#L124) 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 the position in `sqlmock.Rows` gets incremented and so... the second query has no more rows to scan. – mkopriva Feb 02 '20 at 09:32
  • Thank you @mkopriva, would you please add it as an answer? – Zeinab Abbasimazar Feb 02 '20 at 13:25

1 Answers1

2

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.

mkopriva
  • 35,176
  • 4
  • 57
  • 71