I had the same drama as @GetFuzzy above - it seemed that no matter what I did I couldn't avoid the NullReferenceException whenever an Include() call was made on a Moq DbSet. The Github example in the other answer unfortunately did not work: Set.Include() always returns null.
After fiddling for a while I came up with a workaround for this.
[Test]
public void CanUseIncludeWithMocks()
{
var child = new Child();
var parent = new Parent();
parent.Children.Add(child);
var parents = new List<Parent> { parent };
var children = new List<Child> { child };
var parentsDbSet1 = new FakeDbSet<Parent>();
parentsDbSet1.SetData(parents);
var parentsDbSet2 = new FakeDbSet<Parent>();
parentsDbSet2.SetData(parents);
parentsDbSet1.Setup(x => x.Include(It.IsAny<string>())).Returns(parentsDbSet2.Object);
// Can now test a method that does something like: context.Set<Parent>().Include("Children") etc
}
public class FakeDbSet<T> : Mock<DbSet<T>> where T : class
{
public void SetData(IEnumerable<T> data)
{
var mockDataQueryable = data.AsQueryable();
As<IQueryable<T>>().Setup(x => x.Provider).Returns(mockDataQueryable.Provider);
As<IQueryable<T>>().Setup(x => x.Expression).Returns(mockDataQueryable.Expression);
As<IQueryable<T>>().Setup(x => x.ElementType).Returns(mockDataQueryable.ElementType);
As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(mockDataQueryable.GetEnumerator());
}
}
I really don't like the clumsiness of having to have two fake DbSets but for some reason this doesn't work:
parentsDbSet1.Setup(x => x.Include(It.IsAny<string>())).Returns(parentsDbSet1.Object);
anyone have an explanation for this?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…