Entity framework 6 mocking include method on dbset

前端 未结 3 725
庸人自扰
庸人自扰 2020-12-13 15:16

Have been googling for a solution to the problem on how to mock the include method on dbset in EF6. The problem is well documented here :-

http://entityframework.c

3条回答
  •  醉话见心
    2020-12-13 15:52

    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 };
        var children = new List { child };
    
        var parentsDbSet1 = new FakeDbSet();
        parentsDbSet1.SetData(parents);
    
        var parentsDbSet2 = new FakeDbSet();
        parentsDbSet2.SetData(parents);
    
        parentsDbSet1.Setup(x => x.Include(It.IsAny())).Returns(parentsDbSet2.Object);
    
        // Can now test a method that does something like: context.Set().Include("Children") etc
    }
    
    
    public class FakeDbSet : Mock> where T : class
    {
        public void SetData(IEnumerable data)
        {
            var mockDataQueryable = data.AsQueryable();
    
            As>().Setup(x => x.Provider).Returns(mockDataQueryable.Provider);
            As>().Setup(x => x.Expression).Returns(mockDataQueryable.Expression);
            As>().Setup(x => x.ElementType).Returns(mockDataQueryable.ElementType);
            As>().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())).Returns(parentsDbSet1.Object);
    

    anyone have an explanation for this?

提交回复
热议问题