I\'d like to give the background to this question. Skip if you like. For quite a while I\'ve paid close attention to the on going debates on stackoverflow and elsewhere rega
I managed to mock Include in Moq with a generic approach. Albeit this doesn't cover all usages of Include(), only with string and Expression, but it suited my needs:
public Mock> SetupMockSetFor(Expression>> selector) where T : class
{
var mock = new Mock>();
mock.ResetCalls();
this.EntitiesMock.Setup(m => m.Set()).Returns(mock.Object);
this.EntitiesMock.Setup(selector).Returns(mock.Object);
mock.Setup(x => x.Include(It.IsAny())).Returns(mock.Object);
try
{
mock.Setup(x => x.Include(It.IsAny>>()))
.Returns(mock.Object);
}
catch
{
// Include only applies to some objects, ignore where it doesn't work
}
return mock;
}
test usage:
var mockCourseSet = SetupMockSetFor(entities => entities.Courses);
In service method:
var foundCourses = dbContext.Courses.Include(c => c.CourseParticipants).Where(c => c.Id = courseId)