Entity framework 6 mocking include method on dbset

前端 未结 3 710
庸人自扰
庸人自扰 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:45

    So, this is possible if a bit of a faff!

    In the below I setup the mock context and sets and can call include successfully. I think that the secret sauce is in stubbing the calls through to Provider, Expression and GetEnumerator and in setting the DbSet properties on the stubbed context to the stubbed sets and not stubbing the context to returning them.

    A runnable example is available on GitHub

        [Test]
        public void CanUseIncludeWithMocks()
        {
            var child = new Child();
            var parent = new Parent();
            parent.Children.Add(child);
    
            var parents = new List
                {
                    parent
                }.AsQueryable();
    
            var children = new List
                {
                    child
                }.AsQueryable();
    
            var mockContext = MockRepository.GenerateStub();
    
            var mockParentSet = MockRepository.GenerateStub>();
            var mockChildSet = MockRepository.GenerateStub>();
    
            mockParentSet.Stub(m => m.Provider).Return(parents.Provider);
            mockParentSet.Stub(m => m.Expression).Return(parents.Expression);
            mockParentSet.Stub(m => m.GetEnumerator()).Return(parents.GetEnumerator());
    
            mockChildSet.Stub(m => m.Provider).Return(children.Provider);
            mockChildSet.Stub(m => m.Expression).Return(children.Expression);
            mockChildSet.Stub(m => m.GetEnumerator()).Return(children.GetEnumerator());
    
            mockContext.Parents = mockParentSet;
            mockContext.Children = mockChildSet;
    
            mockContext.Parents.Should().HaveCount(1);
            mockContext.Children.Should().HaveCount(1);
    
            mockContext.Parents.First().Children.FirstOrDefault().Should().NotBeNull();
    
            var query = mockContext.Parents.Include(p=>p.Children).Select(pc => pc);
    
            query.Should().NotBeNull().And.HaveCount(1);
            query.First().Children.Should().NotBeEmpty().And.HaveCount(1);
    
        }
    

提交回复
热议问题