How to mock Dapper call to execute stored procedures with parameters?

489 Views Asked by At

I am using the following line in my code to execute the stored procedure,

var parameters = new DynamicParameters();
parameters.Add("MYPARAM", field.ListPickListCode, DbType.String, ParameterDirection.Input, int.MaxValue);

options = dbConn.QuerySingleOrDefault<string>(sql: "mysp", param: parameters, commandType: CommandType.StoredProcedure);

How should I set up my mock?

I tried below 2 mocking ways, but both failed,

var parameters = new DynamicParameters();
parameters.Add("MYPARAM", fieldDefinition.ListPickListCode, DbType.String, ParameterDirection.Input, int.MaxValue);

IDynamicDatabaseConnection dbConnMock = A.Fake<IDynamicDatabaseConnection>();
A.CallTo(() => dbConnMock.QuerySingleOrDefault<string>("mysp")).Returns("someValue");

And,

var parameters = new DynamicParameters();
parameters.Add("MYPARAM", fieldDefinition.ListPickListCode, DbType.String, ParameterDirection.Input, int.MaxValue);

IDynamicDatabaseConnection dbConnMock = A.Fake<IDynamicDatabaseConnection>();
A.CallTo(() => dbConnMock.QuerySingleOrDefault<string>("mysp", parameters, null, null, CommandType.StoredProcedure)).Returns("someValue");
1

There are 1 best solutions below

2
Blair Conrad On

As @Hayden says, we could likely help better if you supplied the errors. However, QuerySingleOrDefault appears to be an extension method, if I've found the right source. As noted in the documentation, FakeItEasy cannot override static methods (including extension methods). As has been answered elsewhere, if you find it necessary to fake an extension method (as opposed to refactoring your code to provide an alternative implementation), the closest approach can be to fake the methods that the extension methods exercise on the original interface. This works best for very simple extension methods, and can become quiet brittle for complicated ones.