Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add multiple result sets in go-sqlmock?

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?

like image 704
Nikhil Vandanapu Avatar asked Mar 05 '23 21:03

Nikhil Vandanapu


2 Answers

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

like image 67
Sanjeev Siva Avatar answered Mar 09 '23 05:03

Sanjeev Siva


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.

like image 36
Nikhil Vandanapu Avatar answered Mar 09 '23 07:03

Nikhil Vandanapu