NSubstitute.Community.DbConnection 2.13.0

dotnet add package NSubstitute.Community.DbConnection --version 2.13.0                
NuGet\Install-Package NSubstitute.Community.DbConnection -Version 2.13.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NSubstitute.Community.DbConnection" Version="2.13.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add NSubstitute.Community.DbConnection --version 2.13.0                
#r "nuget: NSubstitute.Community.DbConnection, 2.13.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install NSubstitute.Community.DbConnection as a Cake Addin
#addin nuget:?package=NSubstitute.Community.DbConnection&version=2.13.0

// Install NSubstitute.Community.DbConnection as a Cake Tool
#tool nuget:?package=NSubstitute.Community.DbConnection&version=2.13.0                

NSubstitute.DbConnection

A powerful and flexible extension to NSubstitute for mocking database queries

If there's anything you need to do that's not covered below then raise an Issue and we'll see about adding it!

Installation

The package is available from nuget.org as NSubstitute.Community.DbConnection

Or, you can run install-package NSubstitute.Community.DbConnection from within your IDE

Getting started

To get started, create a mock connection by calling .SetupCommands() on a regular NSubstitute IDbConnection mock:

    var mockConnection = Substitute.For<IDbConnection>().SetupCommands();

or, if you want async support, use DbConnection instead of IDbConnection - either works fine here:

    var mockConnection = Substitute.For<DbConnection>().SetupCommands();

You can then fluently add behaviour to your mock connection using the .SetupQuery() methods below, starting with some relative "greedy" matching by default, simply on the query text passed in, but with the ability to match parameter values if you need and also match parts of the query text.

You can define single or multiple result sets, using anonymous types or concrete types, including record types.

Set up a simple query

Set up a query using .SetupQuery() and the expected query text, then specify the response using .Returns() and an array of anonymous types:

    mockConnection.SetupQuery("select * from MyTable").Returns(
        new { Foo = 1, Bar = "abc" },
        new { Foo = 2, Bar = "def" }
    );

That's all you need to do - executing this query against the connection will return the specified results:

    using var command = mockConnection.CreateCommand();
    command.CommandText = "select * from table";
    mockConnection.Open();
    using var reader = command.ExecuteReader();

    reader.Read();
    reader["Foo"].Should().Be(1);
    reader["Bar"].Should().Be("abc");

    reader.Read();
    reader["Foo"].Should().Be(2);
    reader["Bar"].Should().Be("def");

Works with async

You'll also get the correct mocked behaviour using the async API

    await using var command = mockConnection.CreateCommand();
    command.CommandText = "select * from table";
    await mockConnection.OpenAsync();
    await using var reader = command.ExecuteReaderAsync();

    await reader.ReadAsync();
    reader["Foo"].Should().Be(1);
    reader["Bar"].Should().Be("abc");

    await reader.ReadAsync();
    reader["Foo"].Should().Be(2);
    reader["Bar"].Should().Be("def");

Works with Dapper

Because Dapper uses the same calls to DbConnection under the hood, you'll get the correct mocked behaviour here too:

    var result = mockConnection.Query<(int Foo, string Bar)>("select * from table").ToList();

    reader[0].Foo.Should().Be(1);
    reader[0].Bar.Should().Be("abc");
    reader[1].Foo.Should().Be(2);
    reader[1].Bar.Should().Be("def");

Query parameters

Use .WithParameter() to also match on the value of a parameter passed to the query (by default, a query will match on just the command text, ignoring any parameter values):

    mockConnection.SetupQuery("select * from table where Id = @id")
        .WithParameter( "id", 1)
        .Returns(new { Id = 1, Name = "The first one"});

    mockConnection.SetupQuery("select * from table where Id = @id")
        .WithParameter( "id", 2)
        .Returns(new { Id = 2, Name = "The second one"});

You can add multiple parameters by chaining calls to .WithParameter() or by using a single call to WithParameters()

You can also force a query to match only if no parameters are passed by calling .WithNoParameters()

Query text matching

In addition to supplying just the query text to match against, you can also supply a delegate or a regular expression:

    mockConnection.SetupQuery(queryText => queryText.Contains("from MyTable"))
        .Returns(new { Foo = 1, Bar = "abc" });

    mockConnection.SetupQuery(new Regex("select .+ from"))
        .Returns(new { Foo = 1, Bar = "abc" });

Concrete result types

As well as anonymous types, you can also use concrete types (including record types) as result types:

public class KeyValue
{
    public int Key { get; set; }

    public string Value { get; set; }
}
public record KeyValueRecord(int Key, string Value);
    mockConnection.SetupQuery("select * from MyTable")
        .Returns(new KeyValue { Key = 1, Value = "abc" });

    mockConnection.SetupQuery("select * from MyTable")
        .Returns(new KeyValueRecord(1, "abc"));

Multiple result sets

Use .ThenReturns() to set up second and subsequent result sets for your query:

    mockConnection.SetupQuery("select * from MyTable")
        .Returns(new { Never = 1, Eat = 1 })
        .ThenReturns(new { Shredded = 3, Wheat = 4 });
    );

    using var command = mockConnection.CreateCommand();
    command.CommandText = "select * from table";
    mockConnection.Open();
    using var reader = command.ExecuteReader();

    reader.Read();
    reader["Never"].Should().Be(1);
    reader["Eat"].Should().Be(2);

    reader.NextResult();

    reader.Read();
    reader["Shredded"].Should().Be(3);
    reader["Wheat"].Should().Be(4);

Throws an exception

Use .Throws() to simulate the scenario when an exception is expected.

    mockConnection.SetupQuery("delete from TableWithTriggerPreventDelete")
        .Throws(new Exception());

Further examples

Check out the test fixtures in NSubstitute.DbConnection.Tests and NSubstitute.DbConnection.Dapper.Tests for working examples of the full set of supported functionality.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.13.0 538 10/24/2024
2.12.0 4,028 8/5/2024
2.11.0 91 8/2/2024
2.10.0 89 8/2/2024
2.9.0 202 8/1/2024
2.8.0 11,223 11/3/2022
2.7.0 1,211 5/30/2022
2.6.0 921 5/26/2022
2.5.0 909 5/25/2022
2.4.0 923 3/17/2022
2.3.1 888 3/16/2022
2.3.0 920 3/16/2022
2.2.0 1,006 3/11/2022
2.1.0 917 3/10/2022
2.0.1 908 3/10/2022
2.0.0 940 3/10/2022
1.2.1 923 3/9/2022
1.2.0 940 3/9/2022
1.1.0 941 3/9/2022
1.0.1 939 3/7/2022
1.0.0 932 3/7/2022

Added support for Dapper QueryBuilder