views:

43

answers:

3

Hello, 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.

+1  A: 

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
Yes, thanks for the help, but there must be a way to unit test maybe without mocking the method?
A: 

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
+1  A: 

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:

Making extension methods amenable to mocking

How to mock extension methods

adrift