Reputation: 761
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
Upvotes: 1
Views: 2382
Reputation: 41
Query-method is an extension method if I remember correctly and cannot AFAIK be mocked like that with moq.
Upvotes: 4
Reputation: 5493
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());
Upvotes: 3
Reputation: 733
As a matter of interest - how have you got your layers setup? It looks like your using a concrete NHibernateSession, which would make it very difficult to mock anyway. My advice would be to use the ISession, which you should then be able to mock easily.
I'm not familiar with Rhino, but using Moq I would have done :
Mock<ISession> MockSession = new Mock<ISession>();
MockSession.Setup(x => x.Query<It.IsAny<Job>()>())
.Returns(new Lis<Job> { new Job()}.AsQueryable());
Typically, interfaces are easier to mock than concrete classes. In fact, the only place I use a concrete class is in the static configuration method I have to setup my IoC container. Everywhere else, I use interfaces. This way, my unit tests kinda produce themselves! :)
Hope this is of some use!
Happy coding,
Cheers,
Chris.
Upvotes: 2