0

I am trying to Mock some code that calls an extension method. This is legacy code that is not written to be testable, but I've been tasked with trying to create unit tests for it without having to change the code, as time/politics/etc will now allow for that.

Anyway, the code I'm trying to mock is in our applications data access framework. We use a (very old) version of NHibernate (hence legacy). We have a method that uses nHibernate to return an IQueryable interface for us to query. It looks like this:

    public static IQueryable<TEntity> Linq()
    {
        ISession session = GetCurrentUnitOfWork();

        return session.Query<TEntity>();
    }

I can successfully rig the GetCurrentUnitOfWork method to return an mocked ISession, which, instead of going to the DB, returns Lists of objects.

The problem is that the Query method is not defined on ISession. It's an extension method of ISession. Since the framework code is compiled to call the extension method Query(), even if I define the exact same method on my mocked ISession, the extension method is still called.

So, does anybody have any ideas on how I can rig this code to call a mocked version of the Query method()?

Thanks in advance.

jeff.eynon
  • 1,296
  • 3
  • 11
  • 29
  • There are a couple of threads, how to mock the static methods, have a look at [this](https://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq) and [this](https://stackoverflow.com/questions/562129/how-do-i-use-moq-to-mock-an-extension-method/562187) – Pavel Anikhouski Apr 01 '19 at 14:49
  • @PavelAnikhouski I saw both of those. The difference is those assume that the extension method is in my code base. In this case, it's not. The extension method is compiled into a 3rd party dll. So it's not necessarily that I have to mock the extension, more like I have to try and redirect it. – jeff.eynon Apr 01 '19 at 15:08

1 Answers1

1

I would suggest using reflection to look at what methods the Query<> extension is calling on the ISession object, and then mock those methods on the ISession and leave the Query extension alone.

David McNee
  • 137
  • 1
  • 2
  • 10
  • I thought about that, and as a last resort that's what I'll do. It seems like a big giant rabbit hole waiting for me to get lost in though :) – jeff.eynon Apr 01 '19 at 15:09