go-sqlmock is a Go library that simulates SQL driver behavior for unit testing by intercepting database calls through the standard database/sql/driver interface, eliminating the need for a real database connection. It provides a comprehensive mocking framework that allows developers to define expectations for SQL operations, including queries, executions, prepared statements, and transaction lifecycles, with precise control over the results and errors returned.
The library distinguishes itself through its flexible matching and verification capabilities. It supports regex-based or exact SQL string matching, along with a custom argument matching interface that handles complex types like time.Time and provides wildcard matchers for flexible value comparison. Expectations can be enforced in a predefined order, and the library verifies that all registered expectations are fulfilled during the test, reporting any unmatched or missing calls. It also includes configurable delayed response simulation for testing timeout and context cancellation scenarios.
Beyond core query and exec mocking, go-sqlmock covers the full spectrum of database interaction testing. This includes simulating connection health through ping calls and sentinel errors, managing transaction begin/commit/rollback cycles with configurable errors, and building mock result sets with detailed column metadata such as names, types, nullability, and precision. The library also supports multiple result sets, named parameters, and session state reset, providing a complete toolkit for validating database interaction logic in Go tests.