简体   繁体   中英

Mocking Entity Framwork using Moq not returning DbSet<T>

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.

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);

Is there a way to return a null value? so instead of: .Returns(GetDbSetMock(departments).Object); Something like this? .Returns(GetDbSetMock(null).Object); I have a unit test that is looking for a null response from the database.

Not sure how to mock it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM