DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.15k stars 407 forks source link

How to use multiple cases and multiple expect in SqlMock #196

Closed wanfintara closed 5 years ago

wanfintara commented 5 years ago

the test cases

tests := []struct {
    name           string
    fields         fields
    args           args
    expectedBegin  *sqlmock.ExpectedBegin
    expectedOrder  *sqlmock.ExpectedQuery
    expectedDetail *sqlmock.ExpectedExec
    wantSQL        bool
    wantErr        bool
}{
    {
        name:   "Test 1: Success",
        fields: fields{db: dbMock},
        args: args{
            order:  order,
            detail: orderDetail,
        },
        expectedBegin: mock.ExpectBegin(),
        expectedOrder: mock.ExpectQuery(queryOrder).
            WithArgs(sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()).
            WillReturnRows(rows),
        expectedDetail: mock.ExpectExec(queryDetail).
            WithArgs(sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()).
            WillReturnResult(sqlmock.NewResult(0, 1)),
        wantSQL: true,
        wantErr: false,
    },
}

for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        or := orderRepo{
            db: tt.fields.db,
        }

        if err := or.CreateOrder(tt.args.order, tt.args.detail); (err != nil) != tt.wantErr {
            t.Errorf("orderRepo.CreateOrder() error = %v, wantErr %v", err, tt.wantErr)
        }

        if tt.wantSQL {
            if err := mock.ExpectationsWereMet(); err != nil {
                t.Errorf("there were unfulfilled expectations: %s", err)
            }
        }
    })
}

i got

there were unfulfilled expectations: there is a remaining expectation which was not matched: ExpectedBegin => expecting database transaction Begin

am I missing something here??

l3pp4rd commented 5 years ago

Hi, you can figure this out on your own, using an additional abstraction can also help to simplify