UnoSD / Moq.Dapper

Moq extensions for Dapper methods.
GNU General Public License v2.0
173 stars 78 forks source link

NullReferenceException when using parameters #1

Closed faniereynders closed 7 years ago

faniereynders commented 7 years ago

Dapper throws a NullReferenceException when parameters are used in a command.

Given the following test scenario, the exception occurs:

[Test]
public void ExecuteScalar()
{
    var connection = new Mock<IDbConnection>();

    const int expected = 77;

    connection.SetupDapper(c => c.ExecuteScalar<int>(It.IsAny<string>(), It.IsAny<object>(), null, null, null))
              .Returns(expected);

    var actual = connection.Object.ExecuteScalar<int>(
        "select * from people where id = @id", new { id = 1 }, null, null);

    Assert.That(actual, Is.EqualTo(expected));
}

Stack trace:

   at ParamInfo44e2be98-d8bb-4358-8537-1dc2da8dc716(IDbCommand , Object )
   at Dapper.CommandDefinition.SetupCommand(IDbConnection cnn, Action`2 paramReader)
   at Dapper.SqlMapper.ExecuteScalarImpl[T](IDbConnection cnn, CommandDefinition& command)
   at Dapper.SqlMapper.ExecuteScalar[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType)

When no parameters are used in the command, it works.

After investigation I found this

It turns out that Dapper internally needs to add parameters to the IDbCommand.Parameters collection and this is currently null.

UnoSD commented 7 years ago

Thanks for bringing this up, I will have a look at it and merge the PR when I get a chance.

UnoSD commented 7 years ago

Merged PR. Thanks.