go-sqlmock

A mock sql/driver implementation for Go that simulates database behavior in tests without a real database connection.

Library
Go
vv1.5.2
6,567stars
Custom / Unknown

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
56/100Fair
Development Activity36
Maintenance28
Community60
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
70/100Good
Architecture76
Code Quality78
Innovation64
Learning Curve60

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.DB wired to an in-memory mock connection
  • Fluent Expect* builders (ExpectQuery, ExpectExec, ExpectBegin, ExpectCommit, ExpectRollback, ExpectPrepare, ExpectPing, ExpectClose) for every driver-level operation
  • A Rows builder for constructing mocked query results from Go values or a CSV string, including per-row and close errors
  • A pluggable QueryMatcher interface (regexp by default, exact-match alternative included) for controlling how expected SQL is compared to actual SQL
  • An Argument interface for matching individual bind parameters by custom logic (e.g. “any time.Time”) instead of exact value equality
  • WillDelayFor support 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/sql without a live test database
  • Asserting that a transaction correctly commits on success and rolls back when an inner Exec fails
  • 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

Go
82%
AGPL 3.0

Beta9

Developer Tools · AI Development · Data Engineering

1,762

Run AI workloads at scale with a Pythonic serverless runtime that handles GPU inference, background jobs, and sandboxes with zero infrastructure overhead.

View details
84
Repo Health
78
Technical
67
Dependency
Built with
Go82%
Python17%
Updated 3 days ago
Go
75%
AGPL 3.0

Coder

Devops · Developer Tools · Code Editors

14,299

Self-hosted cloud development environments and AI coding agents — defined in Terraform, connected via WireGuard, automatically shut down when idle.

View details
93
Repo Health
90
Technical
69
Dependency
Built with
Go75%
TypeScript23%
Updated today
Go
68%
MIT

Gogs

Developer Tools

47,783

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.

View details
96
Repo Health
79
Technical
72
Dependency
Built with
Go68%
Go Template16%
TypeScript10%
Updated 4 days ago
TypeScript
49%
AGPL 3.0

Grafana

Monitoring · Analytics

76,498

The open-source observability platform that unifies metrics, logs, and traces from any data source into dynamic, queryable dashboards.

View details
95
Repo Health
91
Technical
65
Dependency
Built with
TypeScript49%
Go45%
Updated today
Go
91%
AGPL 3.0

Lago

Ecommerce · Invoicing Finance

10,444

Open-source metering, billing, and revenue infrastructure for product-led companies that need complete control over their pricing stack.

View details
86
Repo Health
81
Technical
74
Dependency
Built with
Go91%
Updated 2 days ago
Go
44%
GPL 3.0

Netdata

Monitoring · Devops

80,357

Real-time per-second metrics, ML-powered anomaly detection, and zero-config observability for any infrastructure.

View details
93
Repo Health
86
Technical
71
Dependency
Built with
Go44%
C32%
Rust15%
Updated today
Go
74%
Other

Notifuse

Marketing

2,089

Open-source, self-hosted alternative to Mailchimp, Brevo, and Klaviyo — send newsletters and transactional emails without per-email pricing or vendor lock-in.

View details
83
Repo Health
80
Technical
66
Dependency
Built with
Go74%
TypeScript23%
Updated yesterday
Dart
61%
GPL 3.0

Owlistic

Note Taking · Productivity

432

Self-hosted, open-source real-time note-taking and task management with WYSIWYG editing, live sync, and role-based access control.

View details
46
Repo Health
74
Technical
71
Dependency
Built with
Dart61%
Go39%
Updated yesterday
TypeScript
52%
Other

SigNoz

Monitoring · Analytics

31,972

Self-host your entire observability stack — logs, metrics, traces, and LLM monitoring — in one OpenTelemetry-native platform, without the Datadog bill.

View details
92
Repo Health
83
Technical
69
Dependency
Built with
TypeScript52%
Go37%
Updated today

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search