简体   繁体   中英

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?

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.

You have to get your test rows inside a struct and then execute loop over the struct like below code.

 type args struct {
        val string
 }

 tests := []struct {
            name    string
            s       *<YourDBstruct>
            args    args
            wantErr bool
        }{
            {
                name:    "Test with correct value1",
                s:       &YourDBstruct{db},
                args:    args{"Val1"}
                wantErr: true,
            },
            {
                name:    "Test with correct value2",
                s:       &YourDBstruct{db},
                args:    args{"Val2"}
                wantErr: true,
            },
            {
                name:    "Test with correct valueN",
                s:       &YourDBstruct{db},
                args:    args{"ValN"}
                wantErr: true,
            },
        }
        for _, tt := range tests {
            t.Run(tt.name, func(t *testing.T) {
                mock.ExpectExec("my_stored_procedure")
                if err := tt.s.YourStoreFuncName(); (err != nil) != tt.wantErr {
                    t.Errorf("YourStoreFuncName() error = %v, wantErr %v", err, tt.wantErr)
                }
            })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM