Assemblies to assist testing Dapper database invocations
Install-Package Dapper.MoqTests
Or
Install-Package Dapper.MoqTests.Core
Note: With version 1.0.0+ the library is compiled against .net 4.6.1 therefore is now compatible with .net standard projects.
Tested and confirmed to work with Dapper v1.60.0 and Moq v4.14.7
connection.Query<int>(@"select count(*)
from Table
where Name = @name", new { name = "anything" })
using Dapper.MoqTests;
public void Test()
{
var connection = new MockDbConnection();
var repository = new MyTestRepository(connection);
repository.ReadNames();
connection.Verify(c => c.Query<int>(@"select count(*)
from Table
where Name = @name", new { name = "anything" }, It.IsAny<IDbTransaction>(), true, null, null));
}
using Dapper.MoqTests;
public void Test()
{
var connection = new MockDbConnection();
var repository = new MyTestRepository(connection);
repository.DeleteSomething();
connection.Verify(c => c.Execute(@"delete
from Table
where Name = @name", new { name = "to-be-deleted" }, It.IsAny<IDbTransaction>(), true, null, null));
}
using Dapper.MoqTests;
using System.Data;
public void Test()
{
var connection = new MockDbConnection();
var repository = new MyTestRepository(connection);
var data = new DataTable
{
Columns =
{
"name"
},
Rows =
{
"Bloggs",
"Smith"
}
};
connection
.Setup(c => c.Query<string>(@"select name
from Table
where Enabled = 1", It.IsAny<object>(), It.IsAny<IDbTransaction>(), true, null, null))
.Return(new DataTableReader(data))
repository.ReadNames();
connection.Verify(c => c.Query<string>(@"select name
from Table
where Enabled = 1", It.IsAny<object>(), It.IsAny<IDbTransaction>(), true, null, null));
}
See more examples here: Samples.cs
- MockDbConnection implements
IDbConnection
- Supports testing of
Query
,Execute
, etc - see What's supported - Compares SQL test case insensitively, ignoring empty lines and leading/trailing white-space
- Compares parameter anonymous objects from different assemblies
- Testing framework isn't restricted, can by NUnit, MsTest or anything else
- Supports Strict execution, pass in the appropriate parameter to the
MockDbConnection
constructor - Supports Async data methods, from version 1.1.0
- Supports verification of method execution times, from version 1.1.0
- Supports verification of transaction usage, from version 1.2.0
- Supports verification of stored procedures & sql text, from version 1.4.0
- Supports verification of command timeout, from version 1.4.0
- Supports customisation of comparisons, from version 1.5.0
- Supports verification of CommandDefinition methods, from version 1.7.0
If you have ideas for improvements or new functionality, etc. Please contribute those ideas by way of raising an issue or creating a pull request with those changes.
I want this library to be the easiest to use by being simple and familiar. I've chosen Moq as the primary source of design at present; by no means do I think it should be tied to this.