How to use pgxmock for testing pgx code
masterpgxmock allows you to simulate pgx behavior without a real database connection. It follows a strict expectation order by default.
To use it:
- Create a mock using
pgxmock.NewPool(). - Define expectations using methods like
ExpectBegin(),ExpectExec(),ExpectCommit(), orExpectRollback(). - Use
WithArgs(...)to match specific arguments in queries. - Use
WillReturnResult(...)orWillReturnError(...)to define the mock's response. - Execute your application logic using the mock object.
- Verify all expectations were met using
mock.ExpectationsWereMet().
Note: Your application code should accept an interface (e.g., PgxIface) that matches the pgx methods you use, allowing you to pass the mock in place of a real connection during tests.
package main
import (
"context"
"fmt"
"testing"
"github.com/pashagolub/pgxmock/v5"
)
// a successful case
func TestShouldUpdateStats(t *testing.T) {
mock, err := pgxmock.NewPool()
if err != nil {
t.Fatal(err)
}
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").
WillReturnResult(pgxmock.NewResult("UPDATE", 1))
mock.ExpectExec("INSERT INTO product_viewers").
WithArgs(2, 3).
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
// now we execute our method
if err = recordStats(mock, 2, 3); err != nil {
t.Errorf("error was not expected while updating: %s", err)
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
// a failing test case
func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {
mock, err := pgxmock.NewPool()
if err != nil {
t.Fatal(err)
}
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").
WillReturnResult(pgxmock.NewResult("UPDATE", 1))
mock.ExpectExec("INSERT INTO product_viewers").
WithArgs(2, 3).
WillReturnError(fmt.Errorf("some error"))
mock.ExpectRollback()
// now we execute our method
if err = recordStats(mock, 2, 3); err == nil {
t.Errorf("was expecting an error, but there was none")
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}