651.288.7000 info@intertech.com

The Dapper Micro ORM (written by StackExchange) is a really fast and slick alternative to the bulky EntityFramework.  I’ve been using it in numerous projects the past year.  The one thing I’ve lamented is the inability to unit test Dapper since it is written using extension methods on IDbConnection.  Recently I found DapperWrapper, which gives you the ability to unit test the Execute and Query methods.  It lacked, however, a wrapper around the Dapper DynamicParameters class.  So if you use this at all (which I do since I use a lot of stored procedures), you are out of luck.

Until now.

I wrote a wrapper called DapperParameters.  It is on NuGet here.  The source for the example shown in this article is on GitHub.

Usage

Here’s a typical usage of the interface IDapperParameters:

  • DependencyInjector is a static class I use to store the container for the SimpleInjector dependency injection package
    • I’m assuming you have set up dependency injection for your project
    • Use DapperParameters as the implementation class of IDapperParameters (when not unit testing)
  • IDbExecutor is the interface created by DapperWrapper that allows us to test Execute and Query
  • IDapperParameters is the parameters interface I wrote
  • In this case, I am adding an input parameter “Parm1”, an output parameter “Output1” and a return value parameter “ReturnValue”
  • Note in the Execute that param is p.DynamicParameters
  • Use Get to retrieve the Output and ReturnValue values

IDapperParameters

The interface IDapperParameters gives you everything that DynamicParameters does and adds some convenience methods for good measure.

Notes:

  • Always pass DynamicParameters to param of Execute or Query method
  • By default, the implementation creates DynamicParameters without a template
  • There is a method called CreateParmsWithTemplate that allows you to create DynamicParameters with a template
  • AddInputParameter has a type template so that unit tests can pass

Unit Test Example

To unit test the above example using Moq, do the following:

Setup

 Test

Conclusion

The story for unit testing Dapper is getting better all the time.  With the addition of DapperParameters, we can now unit test stored procedure calls easily.

For more information on unit testing, see Intertech’s offerings here.

Like What You've Read?

Subscribe to the Blog.

Every Friday we send that week's content from our Developers via email. Try it out!

Some ad blockers can block the form below.

You have Successfully Subscribed!

Pin It on Pinterest

Share This