Last active
January 24, 2022 09:52
-
-
Save eftalyurtseven/db8db8ea7cbef677477762c9692a7411 to your computer and use it in GitHub Desktop.
How to Mock Database with GoMock? - https://medium.com/@eftal/how-to-mock-database-with-gomock-9bd0a92ffc10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func TestMakeAnOrderExecErr(t *testing.T) { | |
ctx := context.Background() | |
req := &orderRequest{ | |
TableNumber: "B-1", | |
Products: map[string]int{ | |
"Pizza": 5, | |
}, | |
} | |
ctrl := gomock.NewController(t) | |
defer ctrl.Finish() | |
pool := mocks.NewMockFakePoolInterface(ctrl) | |
tx := mocks.NewMockTx(ctrl) | |
pool.EXPECT().BeginTx(ctx, pgx.TxOptions{}).Return(tx, nil) | |
insertQuery := `INSERT INTO orders(time, table_number, product_id, product_total) VALUES($1, $2, $3)` | |
execErr := errors.New("tx.Exec failed with err: failed") | |
for k, v := range req.Products { | |
tx.EXPECT().Exec(ctx, insertQuery, time.Now().Format(time.RFC3339), req.TableNumber, k, v).Times(1).Return(nil, execErr) | |
} | |
tx.EXPECT().Rollback(ctx).Times(1).Return(nil) | |
ordersvc := &OrderService{db: pool} | |
_, err := ordersvc.Make(ctx, req) | |
if !errors.Is(err, execErr) { | |
t.Fatalf("erros doesn't matched!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment