Search code examples
c#nhibernateienumerablerhino-mocks

How to mock an NhibernateSession Query that uses a Where clause and returns a List


I cannot work out how to Rhino mock the following statement:

var jobs = nhibernateSession.Query<Job>()
.Where(x => x.Trust.Id == 1)
.ToList();

I have tried various permutations, but the current unsuccessful attempt is:

nhibernateSession.Expect(y => y.Query<Job>())
.IgnoreArguments()
.Return(new List<Job> { new Job() }.AsQueryable());

The error I get back is:

Source: Anonymously Hosted DynamicMethods Assembly
Message: Object reference not set to an instance of an object.
StackTrace:    at lambda_method(Closure , Job )
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

Thanks for any advice.

Stu


Solution

  • Is it because your 'Trust' property is null on the new Job() object you are returning from your mock?

    That would explain the NullReferenceException in the where clause:

    .Where(x => x.Trust.Id == 1)
    

    If this is the problem the fix is:

    nhibernateSession.Expect(y => y.Query<Job>())
        .IgnoreArguments()
        .Return(new List<Job> { new Job{ Trust = new Trust() } }.AsQueryable());