2

Trying to unit test NHibernate and unit of work pattern however have come up against a brick wall when trying to mock data access methods which return an IQueryable?

This works:

var employee = Helper.GetEmployee();
Repository.Stub(x => x.FindById<Employee>(employee.Id)).Return(employee);

This doesn't work:

var employee = Helper.GetEmployee();
var employeeList = new List<Employee> { employee };
Repository.Stub(x => x.All<Employee>().ToList()).Return(employeeList);

Basically, anything which returns > 1 employee I can't get mock to behave.

Repository FindById method returns:

Session.Get<TEntity>(id);

Repository All method returns:

Session.Query<TEntity>();

When unit test runs of mocked repository All method, returns exception saying source can't be null?

I'm stuck, any ideas?

Thanks! Tim

1 Answer 1

1

Have you tried the following. Your data access method is returning an IQueryable, but you're trying to mock what gets returned when you call ToList() on the result? You should just be mocking the result.

Repository.Stub(x => x.All<Employee>()).Return(employeeList.AsQueryable<Employee>);
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Rich, I tried .AsQueryable() but not with the type casting. Will give it a go now thanks :)
I'm assuming your data layer method "All" returns IQueryable<T>, hence the need for AsQueryable<T>
:( No luck Rich. The type is not required as it's actually inferred from the first method call - Stub(x => x.All<Employee>()) still giving me source is null
OK... I can get .All to work however just realised I was using FilterBy :P The following is returning null even though I'm setting it up: repository.Stub(x => x.FilterBy<Employee>(e => e.Active && e.EmployeeID != Guid.Empty)).Return(employeeList.AsQueryable())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.