I'm using Moq to write unit tests that use Entity Framework 6 DbSet
and DbContext
objects. I have a service method with a cascading/multi-level Include
and I can't figure out how to set it up for testing. The service method looks something like this:
return DataContext.Cars
.Include(p => p.Model)
.Include(p => p.Model.Make)
.Select(c => new
{
Key = c.CarId,
Value = string.Format("{0} {1} {2}", c.Model.Make.Name, c.Model.Name, c.Trim)
}
).ToArray();
I know that I have to setup the Include
to return the mocked object, like this:
mockCarDbSet.Setup(m => m.Include(It.IsAny<string>())).Returns(mockCarSet.Object);
But I'm getting a null reference exception from the cascaded .Include(p => p.Model.Make)
. How do I set up Moq to handle multiple levels of Include
?
EDIT
OK, so it turns out that I can't use It.IsAny<string>
for Include
calls that use lambdas instead of strings, so now I have two problems:
- How do I setup a mock with Include that accepts a lambda?
- Will the setup for above cascade to multiple levels?