How to Moq NHibernate extension methods?

c#, linq, moq, nhibernate, ninject

Solution

`Query<T>()` is an extension method, that's why you can't mock it. Although @Roger answer is the way to go, sometimes it's useful to have specific tests. You can start investigating what `Query<T>()` method does - either by reading the NHibernate code, or using your own tests, and set the appropriate methods on ISession.

Warning: creating such a setup will make your test very fragile, and it will break, if the internal implementation of NHibernate changes.

Anyway, you can start your investigation with:

var mockSession = new Mock<ISession>(MockBehavior.Strict); //this will make the mock to throw on each invocation which is not setup
var entities = mockSession.Object.Query<MyEntity>();

The second line above is going to throw an exception and show you which actual property/method on `ISession` the `Query<T>()` extension method tries to access, so you can set it accordingly. Keep going that way, and eventually you will have a good setup for your session so you can use it in the test.

Note: I'm not familiar with NHibernate, but I have used the above approach when I had to deal with extension methods from other libraries.

Problem

I'm developing an application using NHibernate for the ORM, NUnit for unit testing and Ninject for my DI. I'm mocking the ISession like so: ``` var session = new Mock<ISession>(); ``` With the regular non-mocked session objects I can query them with LINQ extension methods like this: ``` var result = Session.Query<MyEntity>(); ``` But when I try to mock this with the following code... ``` session.Setup(s => s.Query<MyEntity>()); ``` ...I get a runtime "Not supported" exception: ``` Expression references a method that does not belong to the mocked object: s => s.Query<MyEntity>() ``` How can I mock basic queries like this in Moq/NHibernate?

Original source

Related problems