Entity framework 6 mocking include method on dbset

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

    using Moq framework this method works with everything I throw at it.

        public static Mock> GetMockSet(this ObservableCollection list) where T : class
        {
            var queryable = list.AsQueryable();
            var mockList = new Mock>(MockBehavior.Loose);
    
            mockList.As>().Setup(m => m.Provider).Returns(queryable.Provider);
            mockList.As>().Setup(m => m.Expression).Returns(queryable.Expression);
            mockList.As>().Setup(m => m.ElementType).Returns(queryable.ElementType);
            mockList.As>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
            mockList.Setup(m => m.Include(It.IsAny())).Returns(mockList.Object);
            mockList.Setup(m => m.Local).Returns(list);
            mockList.Setup(m => m.Add(It.IsAny())).Returns((T a) => { list.Add(a); return a; });
            mockList.Setup(m => m.AddRange(It.IsAny>())).Returns((IEnumerable a) => { foreach (var item in a.ToArray()) list.Add(item); return a; });
            mockList.Setup(m => m.Remove(It.IsAny())).Returns((T a) => { list.Remove(a); return a; });
            mockList.Setup(m => m.RemoveRange(It.IsAny>())).Returns((IEnumerable a) => { foreach (var item in a.ToArray()) list.Remove(item); return a; });
    
            return mockList;
        }
    

    to use it just do:

        mockContext.Setup(p => p.).Returns(.GetMockSet().Object);`
    

    This works grate if the context implements a Interface as you never have to do anything with EF.

    EDIT:

    The reason for the extra bits is we can check the result on the test, if we add or remove we can check the passed collection and it will have the result after the test.

提交回复
热议问题