How I can unit test Dapper Extension Method?

How do I unit test and mock a static extension method with Rhino Mocks?

  • I have following extension method written: static public IQueryable<OutboundPattern> ByClientID(this IQueryable<OutboundPattern> qry, int clientID) { return from p in qry where p.ClientID == clientID select p; } I also have the following service layer method written: public IList<OutboundPattern> OutboundPatterns(int ClientId) { return _outboundpatternRepository.OutboundPatterns().ByClientID(ClientId).ToList(); } I would love to know how to mock with Rhino mocks? I know that static methods and Rhino mocks are no good together? It can not mock statics methods.

  • Answer:

    Daniel Cazzulino has a couple of blog posts that describe an approach to mocking static extension methods. The basic idea is that you take all the static extension methods... and move them to an interface, which can be easily mocked, and make the static class use a factory to construct instances of that interface. This factory can be replaced by a friend test assembly for mocking purposes. This might be more work/change than you would like to make in this case, but it's the only way to do it that I've seen (besides buying TypeMock). Here are his posts: http://www.clariusconsulting.net/blogs/kzu/archive/2009/02/19/Makingextensionmethodsamenabletomocking.aspx http://www.clariusconsulting.net/blogs/kzu/archive/2009/12/22/Howtomockextensionmethods.aspx

user154366 at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

I don't think you can mock extension methods - because they are effectively static methods. In terms of testing you should think about them more as a part of the class that uses them rather than the class on which they are defined (similar to helper methods). As a result I usually use extension methods to do some simple transformation and avoid business logic in them.

Grzenio

What is the class under test at this point? Assuming it is OutboundPatterns, then I'd mock _outboundpatternRepository to return something (a simple list maybe) that only had clients that matched the requested ClientId and maybe again when it is empty. Separate unit tests should be written for the extension method. So to recap, I'd test OutboundPatterns by letting it call the real ByClientID but with strictly controlled data.

mlk

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.