UnoSD / Moq.Dapper

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

ExecuteAsync with StoredProcedure as command type #33

Closed jpepiot closed 5 years ago

jpepiot commented 5 years ago

I get an exception when I try to mock the ExecuteAsync method with StoredProcedure as command type.

var connection = new Mock<DbConnection>();
connection.SetupDapperAsync(c => c.ExecuteAsync(It.IsAny<string>(), It.IsAny<int>(), null, null, null)).ReturnsAsync(10);
var result = await connection.Object.ExecuteAsync("sp_test", new { Id = 1 }, null, null, CommandType.StoredProcedure);
Result StackTrace:  
at ParamInfod786c014-bcd9-49cd-880d-6da8aec447ab(IDbCommand , Object )
   at Dapper.CommandDefinition.SetupCommand(IDbConnection cnn, Action`2 paramReader)
   at Dapper.SqlMapper.TrySetupAsyncCommand(CommandDefinition command, IDbConnection cnn, Action`2 paramReader)
   at Dapper.SqlMapper.ExecuteImplAsync(IDbConnection cnn, CommandDefinition command, Object param)
   at ConsoleApp1.MyTests.DoTest()
--- End of stack trace from previous location where exception was thrown ---
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.

Apparently, it seems that the 'DbParameterCollection' property and the 'CreateDbParameter' method are not mocked, so we get an exception when dapper try to access the Parameter property. If I mock them in the function DbConnectionMockExtensions.SetupNonQueryCommandAsync by adding the following code, I can run my test without error.

   var commandMock = new Mock<DbCommand>();

            commandMock.Protected()
           .SetupGet<DbParameterCollection>(nameof(DbParameterCollection))
           .Returns(new Mock<DbParameterCollection>().Object);

            commandMock.Protected()
                       .Setup<DbParameter>("CreateDbParameter")
                       .Returns(new Mock<DbParameter>().Object);

            mockResult(commandMock, () => result);

Should I add the code and submit a PR ?

UnoSD commented 5 years ago

Sure, please do. As it looks like a small change I may just merge it straightaway and update the package. Thank you for the contribution.

jpepiot commented 5 years ago

I made the PR for the fix. You'll find it at the link below. https://github.com/UnoSD/Moq.Dapper/pull/34

UnoSD commented 5 years ago

Thank you, all merged