{"id":21937857,"url":"https://github.com/apps72/dbmocker","last_synced_at":"2025-08-21T08:30:49.572Z","repository":{"id":43612517,"uuid":"140088155","full_name":"Apps72/DbMocker","owner":"Apps72","description":"Data Mocker for C# DbConnection","archived":false,"fork":false,"pushed_at":"2023-12-19T15:42:13.000Z","size":1994,"stargazers_count":29,"open_issues_count":4,"forks_count":10,"subscribers_count":2,"default_branch":"master","last_synced_at":"2023-12-19T16:05:14.640Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Apps72.png","metadata":{"files":{"readme":"ReadMe.md","changelog":null,"contributing":null,"funding":null,"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}},"created_at":"2018-07-07T13:48:24.000Z","updated_at":"2024-02-04T15:40:57.176Z","dependencies_parsed_at":"2024-02-09T17:47:31.908Z","dependency_job_id":null,"html_url":"https://github.com/Apps72/DbMocker","commit_stats":{"total_commits":76,"total_committers":11,"mean_commits":6.909090909090909,"dds":0.5,"last_synced_commit":"3eb3cf7f0e4221eb17ed218880d11f1b0d7e907c"},"previous_names":[],"tags_count":1,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Apps72%2FDbMocker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Apps72%2FDbMocker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Apps72%2FDbMocker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Apps72%2FDbMocker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Apps72","download_url":"https://codeload.github.com/Apps72/DbMocker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230501172,"owners_count":18236061,"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":[],"created_at":"2024-11-29T01:26:11.304Z","updated_at":"2025-08-21T08:30:49.565Z","avatar_url":"https://github.com/Apps72.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# DbMocker - Simple Database Mocker for UnitTests\n\n## Introduction\n\nThis .NET library simplifies data mocking for UnitTests, to avoid a connection to a relational database.\nDbMocker use the standard Microsoft .NET DbConnection object. So, you can mock any toolkit, \nincluding EntityFramework, Dapper or ADO.NET; And for all database servers (SQL Server, Oracle, SQLite).\n\nFirst, add the [DbMocker NuGet packages](https://www.nuget.org/packages/DbMocker).\nNext, instanciate a `MockDbConnection` and mock you SQL requests using a condition and return a DataTable.\n\nPlease, contact me if you want other features or to solve bugs.\n\n```CSharp\n// Sample method from your DataService\npublic int GetNumberOfEmployees(DbConnection connection)\n{\n    using (var cmd = connection.CreateCommand())\n    {\n        cmd.CommandText = \"SELECT COUNT(*) FROM Employees\";\n        return Convert.ToInt32(cmd.ExecuteScalar());\n    }\n}\n\n/* Create a text file \"123-EMPLOYEES.txt\" with this content\n   And set the build property to \"Embedded resource\".\n        Id        Name          Age\n        (int)     (string)      (int?)\n\n        10        Scott         21\n        20        Bill          NULL\n*/\n\n[TestMethod]\npublic void UnitTest0()\n{\n    var conn = new MockDbConnection();\n\n    // The text file \"123-EMPLOYEES.txt\" is embedded in this project.\n    // See the Samples folder.\n    //  - 123       is an identifier (as you want)\n    //  - EMPLOYEES is the CommandText Tag \n    //    See https://docs.microsoft.com/en-us/ef/core/querying/tags\n    conn.Mocks.LoadTagsFromResources(\"123-EMPLOYEES\");\n\n    // Call your \"classic\" methods to tests\n    var data = GetEmployees(conn);\n\n    // DbMocker read the embedded file \n    // and associated the content to the tag\n    Assert.AreEqual(\"Scott\", data[0][1]);\n    Assert.AreEqual(\"Bill\", data[1][1]);\n}\n\n[TestMethod]\npublic void UnitTest1()\n{\n    var conn = new MockDbConnection();\n\n    // When a specific SQL command is detected,\n    // Don't execute the query to your database engine (SQL Server, Oracle, SQLite, ...),\n    // But returns this _Table_.\n    conn.Mocks\n        .When(cmd =\u003e cmd.CommandText.StartsWith(\"SELECT\") \u0026\u0026\n                     cmd.Parameters.Count() == 0)\n        .ReturnsTable(MockTable.WithColumns(\"Count\")\n                               .AddRow(14));\n\n    // Call your \"classic\" methods to tests\n    int count = GetNumberOfEmployees(conn);\n\n    Assert.AreEqual(14, count);\n}\n```\n\nSee [https://apps72.com](https://apps72.com) for more information.\n\n\n\n\n\n\n\n## Conditions\n\nUse the `When` method to describe the condition to be detected. \nThis condition is based on a Lambda expression containing a CommandText or Parameters check.\n\n```CSharp\nconn.Mocks\n    .When(cmd =\u003e cmd.CommandText.StartsWith(\"SELECT\") \u0026\u0026\n                 cmd.Parameters.Count() == 0)\n    .ReturnsTable(...);\n```\n\nUse the `WhenTag` method to detect query containing a row starting with `-- MyTag`. \nThis is compatible with EFCore 2.2, containing a new extension method `WithTag` to identity a request.\n\n```CSharp\nconn.Mocks\n    .WhenTag(\"MyTag\")\n    .ReturnsTable(...);\n``` \n\nUse `WhenAny` to detect all SQL queries. In this case, all queries to the database will return the data specified by WhenAny.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(...);\n```\n\n## ReturnsTable\n\nWhen the previous condition occured, a mocked table will be return:\n\nCreating an new instance of **MockTable**.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(new MockTable().AddColumns(\"ID\", \"Name\")\n                                 .AddRow(1, \"Scott\")\n                                 .AddRow(2, \"Bill\"));\n```\n\nUsing a **MockTable.Empty()** table... to complete.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(MockTable.Empty()\n                           .AddColumns(\"ID\", \"Name\")\n                           .AddRow(1, \"Scott\")\n                           .AddRow(2, \"Bill\"));\n```\n\nUsing a **MockTable.WithColumns()** table... to complete.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(MockTable.WithColumns(\"ID\", \"Name\")\n                           .AddRow(1, \"Scott\")\n                           .AddRow(2, \"Bill\"));\n```\n\nUsing a **MockTable.WithColumns()** typed columns. In this case, columns are defined using a tuple (ColumnName, ColumnType).\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(MockTable.WithColumns((\"ID\", typeof(int?)),\n                                        (\"Name\", typeof(string)))\n                            .AddRow(null, \"Scott\")\n                            .AddRow(2, \"Bill\"));\n```\n\nReturning a **MockTable.SingleCell()** table... to complete.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(MockTable.SingleCell(\"Count\", 14));\n```\n\nUsing an expression to customize the return.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(cmd =\u003e cmd.Parameters.Count() \u003e 0 ? 14 : 99);\n```\n\nusing a **CSV string** with all data.\nThe first row contains the column names.\nThe first data row defines types for each columns (like in a Excel importation).\n\n```CSharp\nstring csv = @\" Id\tName\tBirthdate\n                1\tScott\t1980-02-03\n                2\tBill\t1972-01-12\n                3\tAnders\t1965-03-14 \";\n\nconn.Mocks\n    .WhenAny()\n    .ReturnsTable(MockTable.FromCsv(csv));\n```\n\n## ReturnsRow\n\nWhen a condition occured, a single data row will be return.\nThe specified typed object will generate a MockTable where property names will be the column names\nand proerty values will be the first row data.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsRow(new { Id = 1, Name = \"Denis\" });\n```\n\n\nUsing an expression to customize the return.\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsRow(cmd =\u003e new { Id = 1, Name = \"Denis\" });\n```\n\n## ReturnsScalar\n\nWhen a condition occured, a scalar value will be return:\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsScalar\u003cint\u003e(14);\n```\n\n```CSharp\nconn.Mocks\n    .WhenAny()\n    .ReturnsScalar\u003cint\u003e(cmd =\u003e DateTime.Today.Year \u003e 2000 ? 14 : 0);\n```\n\n## Check the SQL Server query syntax\n\nCall the method `Mocks.HasValidSqlServerCommandText()` \nto check if your string **CommandText** respect the SQL Server syntax...\nwithout connection to SQL Server (but using the [Microsoft.SqlServer.SqlParser](https://www.nuget.org/packages/Microsoft.SqlServer.SqlParser) package).\n\n```CSharp\nconn.Mocks\n    .HasValidSqlServerCommandText()\n    .WhenAny()\n    .ReturnsScalar(14);\n```\n\nSo the `CommandText=\"SELECT ** FROM EMP\"` (double *)\nwill raised a **MockException** with the message \"Incorrect syntax near '*'\".\n\nYou can also define a default value using the `MockDbConnection.HasValidSqlServerCommandText` property.\n\n```CSharp\nvar conn = new MockDbConnection()\n{\n    HasValidSqlServerCommandText = true\n};\n```\n\n## Releases\n\n## Version 1.26\n- #40 Add the Callback support to MockReturns with unit test.\n  Thanks [Tridy](https://github.com/Tridy).\n\n## Version 1.25\n- #36 Accept white list of properties, with `MockTable.FromType` method.\n  Thanks [zewa666](https://github.com/zewa666).\n\n## Version 1.24\n- #35 `MockDbDataReader.GetBytes` does fill the `buffer` param.\n  Thanks [Stepami](https://github.com/Stepami).\n\n## Version 1.23\n- Dependencies updated.\n- #32 Update `MockDbDataReader.IsClosed`\n  Thanks [kiainlogicdk](https://github.com/kiainlogicdk) for the discussion.\n\n## Version 1.22\n- #31 Implement the `DbDataReader.GetSchemaTable()` method.\n  Thanks [javnov](https://github.com/javnov).\n\n## Version 1.21\n- #29 Fix `Dispose` method to change the ConnectionState to Closed.\n  Thanks [OlegKrymskyi](https://github.com/OlegKrymskyi).\n\n## Version 1.20\n- #27 Fix `ExecuteScalar` method to respect the Microsoft documentation.\n  _\"If the first column of the first row in the result set is not found, a null reference is returned. \n  If the value in the database is null, the query returns DBNull.Value.\"_\n  Thanks [Andreas](https://github.com/htw8441).\n\n## Version 1.19\n- Use a direct reference to SqlParser.dll.\n  Thanks [yyalkovich](https://github.com/yyalkovich).\n\n## Version 1.18\n- Add methods `ThrowsException()` to throw an exception when a condition has occured.\n  Thanks [wessonben](https://github.com/wessonben).\n\n## Version 1.17\n- Fix consistent NewLine detection (\\n, \\r or both), used by `WhenTag` method.\n  Thanks [martinsmith1968](https://github.com/martinsmith1968).\n\n## Version 1.16\n- Add `MockTable.FromType\u003cT\u003e` method to fill a mock table using existing .NET objects.\n  Thanks [martinsmith1968](https://github.com/martinsmith1968).\n\n## Version 1.15\n- Fix `MockDbDataReader.IsDBNull` when the value is null.\n\n## Version 1.14\n- Add 'Guid' type in `MockTable.FromFixed` and resource sample files.\n- Add a custom message when a sample conversion fails. Ex: `Invalid conversion of \"2020-01-32\" to \"DateTime\", for column \"Col1\"`.\n\n## Version 1.13\n- Set output value for DbParameter, using `MockResturns.SetParameterValue` method.\n  Thanks [unby](https://github.com/unby).\n- Fix `MockDbDataReader.HasRows` to return true when at least a row is existing.\n  Thanks [htw8441](https://github.com/htw8441).\n\n### Version 1.12\n- Fix the fixed format (resource files) to convert values using Invariant Culture.  \n\n### Version 1.10 and 11\n- Minor fixes to deploy nuget.\n\n### Version 1.9\n- Add `MockResourceOptions.TagSeparator` (default is '-') to allow to include multiple MockTable resource samples. \n  \"01-MyTag.txt\" and \"02-MyTag.txt\" are two resource using the same SQL tag (MyTag).\n\n### Version 1.8\n- Add `Mocks.LoadTagsFromResources` to include MockTable samples described in Embedded resource text files. \n\n### Version 1.7\n- Add `ReturnsDataset` methods to simulate multiple tables (Thanks [stop-cran](https://github.com/stop-cran)).\n- Update the reference to the Nuget **Microsoft.SqlServer.Management.SqlParser** to validate syntaxes of SQL queries.\n\n### Version 1.6\n- Add detailed SQL Query in MockException properties (#6).\n- Add a new WhenTag method (#7).\n- Add a method to validate the syntax of SQL queries without connection to SQL Server (only for SQL Server syntax) (#8).\n\n### Version 1.5\n- Add a `MockColumn` class to manage the column type. See example using \"typed columns\" above.\n- Breaking change: to allow typed MockColumn, the property `MockTable.Columns` is now of type MockColumn[] (previously string[]).\n\n### Version 1.4\n- Add `MockTable.FromCsv(string)` method.\n\n### Version 1.3\n- Add `ReturnsRow(T)` and `ReturnsRow(Func\u003cMockCommand, T\u003e)` methods.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapps72%2Fdbmocker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fapps72%2Fdbmocker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapps72%2Fdbmocker/lists"}