Search code examples
unit-testinggo

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?


Solution

  • 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.