Mocking Entity Framwork使用Moq不返回DbSet <t>

时间:2016-12-12 10:33:35

标签: c# entity-framework-6 moq

我有一个DbSet,我已经嘲笑并暴露了。我把一些部门填满了上下文。当我访问这些部门时,我得到了空。

    private Mock<DbSet<Department>> departmentSet;
    private Mock<DemoEntities> context;

    [TestInitializeAttribute()]
    public void TestInit()
    {
        context = new Mock<DemoEntities>();
        departmentSet = new Mock<DbSet<Department>>();
        context.Setup(c => c.Departments).Returns(departmentSet.Object);
        context.Object.Departments.Add(new Department() { Name = "HR", Id = 1 });
        context.Object.Departments.Add(new Department() { Name = "Operations", Id = 2 });


        context.Object.SaveChanges();

        var list = context.Object.Departments; //returns null
     }

任何人都可以让我知道我做错了什么。因为其他测试用例依赖于访问context.Object.Departments。

1 个答案:

答案 0 :(得分:5)

您需要嘲笑.Set<>,如下所示

 private static Mock<DbSet<T>> GetDbSetMock<T>(IEnumerable<T> items = null) where T : class
        {
            if (items == null)
            {
                items = new T[0];
            }

            var dbSetMock = new Mock<DbSet<T>>();
            var q = dbSetMock.As<IQueryable<T>>();

            q.Setup(x => x.GetEnumerator()).Returns(items.GetEnumerator);

            return dbSetMock;
        }



var mockContext = new Mock<MyDbContext>();

var users = new List<User> { new User { Email = "my@email.com", Id = 1 } };

mockContext.Setup(x => x.Set<User>()).Returns(GetDbSetMock(users).Object);