{"id":13413916,"url":"https://github.com/DATA-DOG/go-sqlmock","last_synced_at":"2025-03-14T20:30:47.211Z","repository":{"id":13909085,"uuid":"16607984","full_name":"DATA-DOG/go-sqlmock","owner":"DATA-DOG","description":"Sql mock driver for golang to test database interactions","archived":false,"fork":false,"pushed_at":"2024-09-11T10:51:41.000Z","size":312,"stargazers_count":6133,"open_issues_count":39,"forks_count":407,"subscribers_count":48,"default_branch":"master","last_synced_at":"2024-10-29T20:33:35.103Z","etag":null,"topics":["database","go","golang","mock","sql","sql-driver","tdd","testing"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DATA-DOG.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["l3pp4rd","gliptak","dolmen","IvoGoman"]}},"created_at":"2014-02-07T07:59:29.000Z","updated_at":"2024-10-29T17:39:29.000Z","dependencies_parsed_at":"2024-06-09T03:22:16.471Z","dependency_job_id":"72441fd7-edb5-4f15-8e86-daa7da6b4f01","html_url":"https://github.com/DATA-DOG/go-sqlmock","commit_stats":{"total_commits":183,"total_committers":44,"mean_commits":4.159090909090909,"dds":0.5901639344262295,"last_synced_commit":"63e2ff0afc421108519f635379d1d52c8cb54039"},"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DATA-DOG%2Fgo-sqlmock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DATA-DOG%2Fgo-sqlmock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DATA-DOG%2Fgo-sqlmock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DATA-DOG%2Fgo-sqlmock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DATA-DOG","download_url":"https://codeload.github.com/DATA-DOG/go-sqlmock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240027414,"owners_count":19736210,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","go","golang","mock","sql","sql-driver","tdd","testing"],"created_at":"2024-07-30T20:01:52.675Z","updated_at":"2025-03-14T20:30:46.864Z","avatar_url":"https://github.com/DATA-DOG.png","language":"Go","readme":"[![Build Status](https://travis-ci.org/DATA-DOG/go-sqlmock.svg)](https://travis-ci.org/DATA-DOG/go-sqlmock)\n[![GoDoc](https://godoc.org/github.com/DATA-DOG/go-sqlmock?status.svg)](https://godoc.org/github.com/DATA-DOG/go-sqlmock)\n[![Go Report Card](https://goreportcard.com/badge/github.com/DATA-DOG/go-sqlmock)](https://goreportcard.com/report/github.com/DATA-DOG/go-sqlmock)\n[![codecov.io](https://codecov.io/github/DATA-DOG/go-sqlmock/branch/master/graph/badge.svg)](https://codecov.io/github/DATA-DOG/go-sqlmock)\n\n# Sql driver mock for Golang\n\n**sqlmock** is a mock library implementing [sql/driver](https://godoc.org/database/sql/driver). Which has one and only\npurpose - to simulate any **sql** driver behavior in tests, without needing a real database connection. It helps to\nmaintain correct **TDD** workflow.\n\n- this library is now complete and stable. (you may not find new changes for this reason)\n- supports concurrency and multiple connections.\n- supports **go1.8** Context related feature mocking and Named sql parameters.\n- does not require any modifications to your source code.\n- the driver allows to mock any sql driver method behavior.\n- has strict by default expectation order matching.\n- has no third party dependencies.\n\n**NOTE:** in **v1.2.0** **sqlmock.Rows** has changed to struct from interface, if you were using any type references to that\ninterface, you will need to switch it to a pointer struct type. Also, **sqlmock.Rows** were used to implement **driver.Rows**\ninterface, which was not required or useful for mocking and was removed. Hope it will not cause issues.\n\n## Looking for maintainers\n\nI do not have much spare time for this library and willing to transfer the repository ownership\nto person or an organization motivated to maintain it. Open up a conversation if you are interested. See #230.\n\n## Install\n\n    go get github.com/DATA-DOG/go-sqlmock\n\n## Documentation and Examples\n\nVisit [godoc](http://godoc.org/github.com/DATA-DOG/go-sqlmock) for general examples and public api reference.\nSee **.travis.yml** for supported **go** versions.\nDifferent use case, is to functionally test with a real database - [go-txdb](https://github.com/DATA-DOG/go-txdb)\nall database related actions are isolated within a single transaction so the database can remain in the same state.\n\nSee implementation examples:\n\n- [blog API server](https://github.com/DATA-DOG/go-sqlmock/tree/master/examples/blog)\n- [the same orders example](https://github.com/DATA-DOG/go-sqlmock/tree/master/examples/orders)\n\n### Something you may want to test, assuming you use the [go-mysql-driver](https://github.com/go-sql-driver/mysql)\n\n``` go\npackage main\n\nimport (\n\t\"database/sql\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\nfunc recordStats(db *sql.DB, userID, productID int64) (err error) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tswitch err {\n\t\tcase nil:\n\t\t\terr = tx.Commit()\n\t\tdefault:\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\tif _, err = tx.Exec(\"UPDATE products SET views = views + 1\"); err != nil {\n\t\treturn\n\t}\n\tif _, err = tx.Exec(\"INSERT INTO product_viewers (user_id, product_id) VALUES (?, ?)\", userID, productID); err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc main() {\n\t// @NOTE: the real connection is not required for tests\n\tdb, err := sql.Open(\"mysql\", \"root@/blog\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tif err = recordStats(db, 1 /*some user id*/, 5 /*some product id*/); err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\n### Tests with sqlmock\n\n``` go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/DATA-DOG/go-sqlmock\"\n)\n\n// a successful case\nfunc TestShouldUpdateStats(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tmock.ExpectBegin()\n\tmock.ExpectExec(\"UPDATE products\").WillReturnResult(sqlmock.NewResult(1, 1))\n\tmock.ExpectExec(\"INSERT INTO product_viewers\").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))\n\tmock.ExpectCommit()\n\n\t// now we execute our method\n\tif err = recordStats(db, 2, 3); err != nil {\n\t\tt.Errorf(\"error was not expected while updating stats: %s\", err)\n\t}\n\n\t// we make sure that all expectations were met\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t}\n}\n\n// a failing test case\nfunc TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tmock.ExpectBegin()\n\tmock.ExpectExec(\"UPDATE products\").WillReturnResult(sqlmock.NewResult(1, 1))\n\tmock.ExpectExec(\"INSERT INTO product_viewers\").\n\t\tWithArgs(2, 3).\n\t\tWillReturnError(fmt.Errorf(\"some error\"))\n\tmock.ExpectRollback()\n\n\t// now we execute our method\n\tif err = recordStats(db, 2, 3); err == nil {\n\t\tt.Errorf(\"was expecting an error, but there was none\")\n\t}\n\n\t// we make sure that all expectations were met\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t}\n}\n```\n\n## Customize SQL query matching\n\nThere were plenty of requests from users regarding SQL query string validation or different matching option.\nWe have now implemented the `QueryMatcher` interface, which can be passed through an option when calling\n`sqlmock.New` or `sqlmock.NewWithDSN`.\n\nThis now allows to include some library, which would allow for example to parse and validate `mysql` SQL AST.\nAnd create a custom QueryMatcher in order to validate SQL in sophisticated ways.\n\nBy default, **sqlmock** is preserving backward compatibility and default query matcher is `sqlmock.QueryMatcherRegexp`\nwhich uses expected SQL string as a regular expression to match incoming query string. There is an equality matcher:\n`QueryMatcherEqual` which will do a full case sensitive match.\n\nIn order to customize the QueryMatcher, use the following:\n\n``` go\n\tdb, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))\n```\n\nThe query matcher can be fully customized based on user needs. **sqlmock** will not\nprovide a standard sql parsing matchers, since various drivers may not follow the same SQL standard.\n\n## Matching arguments like time.Time\n\nThere may be arguments which are of `struct` type and cannot be compared easily by value like `time.Time`. In this case\n**sqlmock** provides an [Argument](https://godoc.org/github.com/DATA-DOG/go-sqlmock#Argument) interface which\ncan be used in more sophisticated matching. Here is a simple example of time argument matching:\n\n``` go\ntype AnyTime struct{}\n\n// Match satisfies sqlmock.Argument interface\nfunc (a AnyTime) Match(v driver.Value) bool {\n\t_, ok := v.(time.Time)\n\treturn ok\n}\n\nfunc TestAnyTimeArgument(t *testing.T) {\n\tt.Parallel()\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Errorf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tmock.ExpectExec(\"INSERT INTO users\").\n\t\tWithArgs(\"john\", AnyTime{}).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\t_, err = db.Exec(\"INSERT INTO users(name, created_at) VALUES (?, ?)\", \"john\", time.Now())\n\tif err != nil {\n\t\tt.Errorf(\"error '%s' was not expected, while inserting a row\", err)\n\t}\n\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t}\n}\n```\n\nIt only asserts that argument is of `time.Time` type.\n\n## Run tests\n\n    go test -race\n\n## Change Log\n\n- **2019-04-06** - added functionality to mock a sql MetaData request\n- **2019-02-13** - added `go.mod` removed the references and suggestions using `gopkg.in`.\n- **2018-12-11** - added expectation of Rows to be closed, while mocking expected query.\n- **2018-12-11** - introduced an option to provide **QueryMatcher** in order to customize SQL query matching.\n- **2017-09-01** - it is now possible to expect that prepared statement will be closed,\n  using **ExpectedPrepare.WillBeClosed**.\n- **2017-02-09** - implemented support for **go1.8** features. **Rows** interface was changed to struct\n  but contains all methods as before and should maintain backwards compatibility. **ExpectedQuery.WillReturnRows** may now\n  accept multiple row sets.\n- **2016-11-02** - `db.Prepare()` was not validating expected prepare SQL\n  query. It should still be validated even if Exec or Query is not\n  executed on that prepared statement.\n- **2016-02-23** - added **sqlmock.AnyArg()** function to provide any kind\n  of argument matcher.\n- **2016-02-23** - convert expected arguments to driver.Value as natural\n  driver does, the change may affect time.Time comparison and will be\n  stricter. See [issue](https://github.com/DATA-DOG/go-sqlmock/issues/31).\n- **2015-08-27** - **v1** api change, concurrency support, all known issues fixed.\n- **2014-08-16** instead of **panic** during reflect type mismatch when comparing query arguments - now return error\n- **2014-08-14** added **sqlmock.NewErrorResult** which gives an option to return driver.Result with errors for\ninterface methods, see [issue](https://github.com/DATA-DOG/go-sqlmock/issues/5)\n- **2014-05-29** allow to match arguments in more sophisticated ways, by providing an **sqlmock.Argument** interface\n- **2014-04-21** introduce **sqlmock.New()** to open a mock database connection for tests. This method\ncalls sql.DB.Ping to ensure that connection is open, see [issue](https://github.com/DATA-DOG/go-sqlmock/issues/4).\nThis way on Close it will surely assert if all expectations are met, even if database was not triggered at all.\nThe old way is still available, but it is advisable to call db.Ping manually before asserting with db.Close.\n- **2014-02-14** RowsFromCSVString is now a part of Rows interface named as FromCSVString.\nIt has changed to allow more ways to construct rows and to easily extend this API in future.\nSee [issue 1](https://github.com/DATA-DOG/go-sqlmock/issues/1)\n**RowsFromCSVString** is deprecated and will be removed in future\n\n## Contributions\n\nFeel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) -\nplease open an issue before, to discuss whether these changes can be accepted. All backward incompatible changes are\nand will be treated cautiously\n\n## License\n\nThe [three clause BSD license](http://en.wikipedia.org/wiki/BSD_licenses)\n\n","funding_links":["https://github.com/sponsors/l3pp4rd","https://github.com/sponsors/gliptak","https://github.com/sponsors/dolmen","https://github.com/sponsors/IvoGoman"],"categories":["Popular","开源类库","Misc","Go","Testing","Test","Open source library","测试","Repositories","Template Engines","Mock","测试相关","测试相关`测试库和测试数据集生成库`","\u003cspan id=\"测试-testing\"\u003e测试 Testing\u003c/span\u003e"],"sub_categories":["测试","Mock","HTTP Clients","Advanced Console UIs","Test","Mock 工具","HTTP客户端","交流","查询语","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDATA-DOG%2Fgo-sqlmock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDATA-DOG%2Fgo-sqlmock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDATA-DOG%2Fgo-sqlmock/lists"}