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,573 stars
Custom / Unknown

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
54 /100 Fair
Development Activity 28
Maintenance 28
Community 60
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
70 /100 Good
Architecture 76
Code Quality 78
Innovation 64
Learning Curve 60

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 12 apps in this directory

Go
84%
AGPL 3.0

Beta9

AI Development · Automation · Data Engineering

1,794

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

View details
85
Repo Health
78
Technical
66
Dependency
Built with
Go 84%
Python 15%
Updated 1 weeks ago
Go
75%
AGPL 3.0

Coder

Code Editors · Developer Tools · Devops

16,729

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

View details
91
Repo Health
90
Technical
65
Dependency
Built with
Go 75%
TypeScript 23%
Updated 1 weeks ago
Go
68%
MIT

Gogs

Developer Tools

47,840

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
87
Repo Health
79
Technical
71
Dependency
Built with
Go 68%
Go Template 16%
Updated 3 weeks ago
TypeScript
48%
AGPL 3.0

Grafana

Analytics · Monitoring

76,962

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
63
Dependency
Built with
TypeScript 48%
Go 46%
Updated 1 weeks ago
Go
88%
AGPL 3.0

Lago

Ecommerce · Invoicing Finance

10,627

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

View details
88
Repo Health
81
Technical
76
Dependency
Built with
Go 88%
Shell 10%
Updated 2 weeks ago
TypeScript
44%
Other

Magic

AI Agents · Automation · Low Code Platforms

5,043

Magic is an enterprise-grade open-source AI agent platform combining a generalist AI agent, workflow engine, IM, and collaborative office system for running an AI-powered digital workforce.

View details
70
Repo Health
79
Technical
65
Dependency
Built with
TypeScript 44%
PHP 32%
Updated 1 months ago
Go
47%
GPL 3.0

Netdata

Devops · Monitoring

80,675

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

View details
93
Repo Health
86
Technical
70
Dependency
Built with
Go 47%
C 30%
Rust 14%
Updated 1 weeks ago
Go
74%
Other

Notifuse

Marketing

2,223

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
81
Repo Health
80
Technical
66
Dependency
Built with
Go 74%
TypeScript 23%
Updated 3 weeks ago
Dart
61%
GPL 3.0

Owlistic

Note Taking · Productivity

433

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

View details
45
Repo Health
74
Technical
70
Dependency
Built with
Dart 61%
Go 39%
Updated 2 weeks ago

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