Can I use the same pgxmock.NewPool() across tests? #214
-
I am testing an API server by doing the following: func TestServer(t *testing.T) {
// Get the swagger description of our API
swagger, err := api.GetSwagger()
require.NoError(t, err)
// Create a new ServeMux for testing.
m := http.NewServeMux()
opts := api.StdHTTPServerOptions{
BaseRouter: m,
}
mockPool, err := pgxmock.NewPool()
require.NoError(t, err)
defer mockPool.Close()
mockdb := db.New(mockPool)
api.HandlerWithOptions(mockdb, opts)
t.Run("ABC", func(t *testing.T) {
mockPool.ExpectQuery(abcQuery).
WithArgs(pgxmock.AnyArg()).
WillReturnRows(abcRow)
rr := testutil.NewRequest().Post("/abc").GoWithHTTPHandler(t, m).Recorder
assert.Equal(t, http.StatusAccepted, rr.Code)
})
t.Run("XYZ", func(t *testing.T) {
mockPool.ExpectQuery(xyzQuery).
WithArgs(pgxmock.AnyArg()).
WillReturnRows(xyzRow)
rr := testutil.NewRequest().Post("/xyz").GoWithHTTPHandler(t, m).Recorder
assert.Equal(t, http.StatusAccepted, rr.Code)
})
} For simplicity I have left out most of the code. What I am seeing is that if I run the tests individually they pass but if I run |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello.
By default pgxmock expects commands to be executed in order. If you run tests in parallel, of course, there is no opportunity to keep that order. It is possible to explicitly ignore the order of the commands: mock, _ := NewConn()
mock.MatchExpectationsInOrder(false)
...
// run your magic Is it a bad pattern to use one global mock? Not really, sometimes (not that often though) you need to stress your code in parallel and that might be a good idea.
I prefer to use local
Best regards |
Beta Was this translation helpful? Give feedback.
Hello.
By default pgxmock expects commands to be executed in order. If you run tests in parallel, of course, there is no opportunity to keep that order. It is possible to explicitly ignore the order of the commands:
Is it a bad pattern to use one global mock? Not really, sometimes (not that often though) you need to stress your code in parallel and that might be a good idea.
I prefer to use local
mockPool
for every test: