Sefik Can Kanber
Sefik Can Kanber

Reputation: 27

How to write a test with xUnit in .NET Core using Dapper.Contrib?

I used Dapper.Contrib in my Asp.Net Core Web API project. I encountered a problem while writing a test with xUnit in this project. For example, here is my method that adds records to my data layer.

   public async Task<bool> AddAsync(User entity)
   {
       await using var connection = _dbConnection.CreateDbConnection();
       await connection.OpenAsync();
       return await connection.InsertAsync(entity) > 0;
   }

My xUnit method that I try to write according to this method is below.

[Fact]
public void AddAsync_Should_Return_As_Expected()
{
    var connection = new Mock<DbConnection>();

    //Arrange
    _userDbConnection.Setup(u => u.CreateDbConnection()).Returns(connection.Object);

    //Act
    var result = _sut.AddAsync(_user).GetAwaiter().GetResult();

    //Assert
    //Assert.Equal(result,actual);
}

When I run this test method, I get object not set error in 'return await connection.InsertAsync(entity) > 0;' line.

What exactly is my fault?

Upvotes: 1

Views: 2925

Answers (1)

Dave Barnett
Dave Barnett

Reputation: 2216

I believe what is happening is you are using a mocked connection and trying to call a Dapper method, InsertAsync, on it. The Dapper method is inevitably failing because it is not a real connection.

I'm not sure how much value you get using mocks here. What you really want to know, when testing AddAsync, is does it actually do what you want it to do which is insert data into the database. So if I were you I would turn this test into an integration test by using a real connection instead of a mocked one. One way of doing this is to

  1. Use a test database for the purposes of testing
  2. Before running the test delete all data from the test database
  3. In your assert use Dapper or otherwise to check that a query for the entity brings back the data you expect to be in the database.

I don't necessarily recommend this but another approach could be to use an in memory database. See for example unit testing Dapper Repositories.

Upvotes: 2

Related Questions