开发者

How can I mock or similarly inject a replacement for the query extension method applied to an NHibernate Session

开发者 https://www.devze.com 2023-01-25 09:18 出处:网络
I am trying to mo开发者_如何学运维ck out or similar the Query extension method applied to an nhibernate-3 session. Similar to the following...

I am trying to mo开发者_如何学运维ck out or similar the Query extension method applied to an nhibernate-3 session. Similar to the following...

public IQueryable<Entity> GetEntities
{
  return entities = Session.Query<Entity>();
}

Where the Query extension method returns an IQueryable collection.

I can clearly mock out the Session object by using Moq or Rhinos. But as of yet not found a suitable way to fake out or replace the extension method. In fact reading answers to several questions on stack overflow, it may not be possible.

see questions How to mock extension methods with Rhino Mock? Mocking Extension Methods with Moq and links within..

I came across the microsoft moles project and thought maybe I could use that to create a subsitute assembly by which I could test this one particular method. Using Pex its relatively quite easy to generate such an assembly however when I try to work a way of using this Assembly its not immediately clear of a way to factor this out.

Ideally I would like to just check to make sure that the query extension method is called by this method and a pre-empted result is returned..

Has anyone done anything similar, would like to hear peoples thoughts..

Ps. there is type mock but I don't have the funds to buy it :)


Extension methods are static methods. So you can't use a mocking library like Rhino Mocks or Moq. (This is a CLR limitation.) TypeMock or Moles get around the limitation by wedging themselves in at the profiler level. (They register themselves as a profiler and inject code into your app domain.)

You can just define your own extension method with the same signature as found in NHibernate.Linq.LinqExtensionMethods:

// NOT RECOMMENDED!!!
public static class MockedSessionExtensions {
    public static IQueryable<T> Query<T>(this ISession session) {
        // your mocked impl goes here
    }
}

The problem with this is it has to be in your production code with some conditional compilation directives around it.

Personally I integration test my repositories against a local database or an in-memory database like SQLite. I then mock out my repositories when testing higher level components. I wouldn't recommend mocking out ISession, ISessionFactory, and the like.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号