I have a db query that returns 2 result sets and I would like to unit test the go function that performs this query. While I can add and test rows like this:
myMockRows:=sqlmock.NewRows([]string{"col1","col2"}).AddRow("col1val1", "col2val2")
mock.ExpectQuery("my_stored_procedure").WithArgs(arg1, arg2).WillReturnRows(myMockRows)
I am not sure how to proceed with creating multiple result sets in my rows
object. How do I do that?
I had tried out, @Nikhil Vandanapu's answer and I wasn't getting the desired output. For some reason it took only myMockRows
and myMockRows2
was ignored. I did some reading and we can do the following to get it to return multiple rows.
myMockRows:=sqlmock.NewRows([]string{"col1","col2"})
.AddRow("col1val1", "col2val2")
.AddRow("col1val1", "col2val2")
mock.ExpectQuery("my_stored_procedure").WillReturnRows(myMockRows)
According to godoc. Value slice return the same instance to perform subsequent actions.
Adding this blog post if you want an easier read about the topic
Do something like this:
myMockRows:=sqlmock.NewRows([]string{"col1","col2"}).AddRow("col1val1", "col2val2")
myMockRows2:=sqlmock.NewRows([]string{"col3","col4"}).AddRow("col3val1", "col4val2")
mock.ExpectQuery("my_stored_procedure").WithArgs(arg1, arg2).WillReturnRows(myMockRows, myMockRows2)
Since WillReturnRows
accepts multiple row objects and forms a slice, use it to construct the next Result Set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With