Mocking Entity Framwork using Moq not returning DbSet

c# entity-framework-6 moq

Question

I have a DbSet which I have mocked and exposed. I have filled some departments to the context. NOw when I access those Departments, I get null.

    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
     }

Can anyone please let me know what I am doing wrong. As the rest of the test cases depend on accessing context.Object.Departments.

1
0
12/12/2016 10:33:35 AM

Accepted Answer

You need to mock the .Set<> as below

 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);
5
12/12/2016 10:43:08 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow