go-sqlmock
A mock sql/driver implementation for Go that simulates database behavior in tests without a real database connection.
Repository Health
Technical Analysis
go-sqlmock implements Go’s database/sql/driver interface, letting you register queued expectations for Begin, Prepare, Query, Exec, Commit, and Rollback calls and have your application code run against them exactly as it would against a real *sql.DB. Because it operates at the driver layer rather than wrapping a specific ORM or query builder, it works with any code that goes through the standard library’s database/sql package, regardless of which real driver (MySQL, Postgres, SQLite, …) is used in production.
Expectations are matched in declaration order by default (configurable to unordered for concurrent tests), and each expectation can be given a driver.Result, a set of mocked rows, a returned error, or an artificial delay. A pluggable QueryMatcher interface controls how the expected SQL string is compared against the actual query — the default treats the expectation as a regular expression, with a stricter case-sensitive equality matcher also built in.
The library is stable and has been the de facto standard for testing Go database code for over a decade, though the maintainer has indicated in the README that they are looking to hand off ownership. It has no runtime dependencies beyond the Go standard library.
What You Get
- A
sqlmock.New()/NewWithDSN()constructor returning a real*sql.DBwired to an in-memory mock connection - Fluent
Expect*builders (ExpectQuery,ExpectExec,ExpectBegin,ExpectCommit,ExpectRollback,ExpectPrepare,ExpectPing,ExpectClose) for every driver-level operation - A
Rowsbuilder for constructing mocked query results from Go values or a CSV string, including per-row and close errors - A pluggable
QueryMatcherinterface (regexp by default, exact-match alternative included) for controlling how expected SQL is compared to actual SQL - An
Argumentinterface for matching individual bind parameters by custom logic (e.g. “any time.Time”) instead of exact value equality WillDelayForsupport on expectations for simulating latency and testing context cancellation/timeout paths
Common Use Cases
- Unit-testing repository/DAO functions that issue raw SQL through
database/sqlwithout a live test database - Asserting that a transaction correctly commits on success and rolls back when an inner
Execfails - Verifying the exact SQL and argument values a code path sends to the database, including prepared-statement reuse
- Simulating database error conditions (connection failure, constraint violation, query timeout) that are hard to reproduce against a real database
- Driving CI test suites that must run fast and without external service dependencies
Under The Hood
Architecture
The package is organized around Go’s database/sql/driver interfaces rather than any application framework. driver.go registers a singleton mockDriver (a connection pool keyed by DSN) with database/sql via sql.Register("sqlmock", pool); New() allocates a fresh DSN, stores a *sqlmock connection in that pool, and calls db.Ping() to force the standard library to actually open it. sqlmock.go implements driver.Conn/driver.Tx (Begin, Prepare, Close, Commit, Rollback) by walking an ordered slice of expectation values (c.expected) and matching the next unfulfilled one against the incoming call — expectations.go defines the concrete Expected* types (ExpectedQuery, ExpectedExec, ExpectedBegin, etc.) that carry the response/error/delay to return. rows.go provides a Rows builder and the driver.Rows-implementing rowSets iterator, including a deliberate buffer-scrubbing step (invalidateRaw) that mimics the standard library’s sql.RawBytes reuse semantics so tests can catch code that holds onto raw byte slices past their valid lifetime. Everything funnels through a single *sqlmock value per DSN, so changing that core struct’s locking model would ripple through every Expect* call site.
Tech Stack
Written in plain Go (module go 1.15) against only the standard library’s database/sql and database/sql/driver packages, with a single external dependency, github.com/kisielk/sqlstruct, used solely inside the examples/ programs rather than the library itself. There is no build tooling beyond go build/go test; historical CI used Travis (.travis.yml) rather than GitHub Actions, and the repo carries no Dockerfile or deployment target since it is a test-only library, not a service.
Code Quality
Every source file has a corresponding _test.go file (18 test files against roughly a dozen source files), using only the standard library testing package — no testify or third-party assertion library — plus Go’s Example* functions, which are compiled and verified against their doc comments by go test. Error handling is explicit throughout: expectation-matching functions return descriptive fmt.Errorf messages naming the specific mismatch rather than swallowing failures, and the codebase includes version-gated files (_before_go18, _go18, _go19) to handle differences in the database/sql/driver interface across Go versions. No linter config or GitHub Actions workflow is present in the current repo snapshot, and the maintainer’s README section explicitly requests a new maintainer, signaling reduced ongoing upkeep.
What Makes It Unique
Rather than mocking at the ORM or query-builder level, go-sqlmock implements the database/sql/driver interface directly, so it works transparently underneath any database/sql-based code regardless of which real driver is used in production — no code changes are needed beyond swapping the driver name in tests. Its QueryMatcher abstraction and custom Argument interface let tests choose between loose regexp matching and strict equality, or write bespoke matchers (e.g. “any timestamp”) for values that can’t be compared by equality, which is a level of matching flexibility most driver-level SQL mocks don’t expose.
Used by 11 apps in this directory
Beta9
Developer Tools · AI Development · Data Engineering
Run AI workloads at scale with a Pythonic serverless runtime that handles GPU inference, background jobs, and sandboxes with zero infrastructure overhead.
Coder
Devops · Developer Tools · Code Editors
Self-hosted cloud development environments and AI coding agents — defined in Terraform, connected via WireGuard, automatically shut down when idle.
Gogs
Developer Tools
The painless self-hosted Git service that runs on anything from a Raspberry Pi to a $5 cloud droplet, delivering GitHub-like workflows as a single Go binary.
Grafana
Monitoring · Analytics
The open-source observability platform that unifies metrics, logs, and traces from any data source into dynamic, queryable dashboards.
Lago
Ecommerce · Invoicing Finance
Open-source metering, billing, and revenue infrastructure for product-led companies that need complete control over their pricing stack.
Netdata
Monitoring · Devops
Real-time per-second metrics, ML-powered anomaly detection, and zero-config observability for any infrastructure.
Notifuse
Marketing
Open-source, self-hosted alternative to Mailchimp, Brevo, and Klaviyo — send newsletters and transactional emails without per-email pricing or vendor lock-in.
Owlistic
Note Taking · Productivity
Self-hosted, open-source real-time note-taking and task management with WYSIWYG editing, live sync, and role-based access control.
SigNoz
Monitoring · Analytics
Self-host your entire observability stack — logs, metrics, traces, and LLM monitoring — in one OpenTelemetry-native platform, without the Datadog bill.