简体   繁体   English

如何使用Entity Framework和Moq进行单元测试?

[英]How do I go about unit testing with Entity Framework and Moq?

I'm new to Moq, and wanting to use it like a backing store for data - but without touching the live database. 我是Moq的新手,想要像数据的后备存储一样使用它 - 但是没有触及实时数据库。

My setup is as follows: 我的设置如下:

  • A UnitOfWork contains all repositories, and is used for data access throughout the application. UnitOfWork包含所有存储库,用于整个应用程序的数据访问。
  • A Repository represents a direct hook into a DbSet, provided by a DbContext. Repository表示由DbContext提供的直接挂钩到DbSet。
  • A DbContext contains all DbSets. DbContext包含所有DbSet。

Here is my test so far: 这是我到目前为止的测试:

        // ARRANGE
        var user = new User()
        {
            FirstName = "Some",
            LastName = "Guy",
            EmailAddress = "some.guy@mockymoqmoq.com",
        };

        var mockSet = new MockDbSet<User>();
        var mockContext = new Mock<WebAPIDbContext>();

        mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object);

        // ACT
        using (var uow = UnitOfWork.Create(mockContext.Object))
        {
            uow.UserRepository.Add(user);
            uow.SaveChanges();
        }

        // ASSERT
        mockSet.Verify(u => u.Add(It.IsAny<User>()), Times.Once());

My test seems to be successful, as it can verify that a user was added to the mock DbSet - but what I need to do is actually get that data back and perform further assertions on it (this is just an ad-hoc test). 我的测试似乎是成功的,因为它可以验证用户是否已添加到模拟DbSet中 - 但我需要做的是实际获取该数据并对其执行进一步的断言(这只是一个临时测试)。

Please advise, testing frameworks are doing my head in. Also, I have the option to move to other testing frameworks if they are easier to use. 请指教,测试框架正在努力。另外,如果它们更容易使用,我可以选择转移到其他测试框架。

Thank you. 谢谢。

Update: Here is my working code. 更新:这是我的工作代码。

Unit Test 单元测试

        // ARRANGE
        var user = new User()
        {
            FirstName = "Some",
            LastName = "Guy",
            EmailAddress = "some.guy@mockymoqmoq.com",
        };

        var mockSet = new MockDbSet<User>();
        var mockContext = new Mock<WebAPIDbContext>();

        mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object);

        // ACT
        using (var uow = UnitOfWork.Create(mockContext.Object))
        {
            uow.UserRepository.Add(user);
            uow.SaveChanges();
        }

        // ASSERT
        mockSet.Verify(u => u.Add(It.IsAny<User>()), Times.Once());

        // TODO: Further assertations can now take place by accessing mockSet.BackingStore.
    }

MockDbSet MockDbSet

class MockDbSet<TEntity> : Mock<DbSet<TEntity>> where TEntity : class
{
    public ICollection<TEntity> BackingStore { get; set; }

    public MockDbSet()
    {
        var queryable = (this.BackingStore ?? (this.BackingStore = new List<TEntity>())).AsQueryable();

        this.As<IQueryable<TEntity>>().Setup(e => e.Provider).Returns(queryable.Provider);
        this.As<IQueryable<TEntity>>().Setup(e => e.Expression).Returns(queryable.Expression);
        this.As<IQueryable<TEntity>>().Setup(e => e.ElementType).Returns(queryable.ElementType);
        this.As<IQueryable<TEntity>>().Setup(e => e.GetEnumerator()).Returns(() => queryable.GetEnumerator());

        // Mock the insertion of entities
        this.Setup(e => e.Add(It.IsAny<TEntity>())).Returns((TEntity entity) =>
        {
            this.BackingStore.Add(entity);

            return entity;
        });

        // TODO: Other DbSet members can be mocked, such as Remove().
    }
}

You just need to create a collection to act as the backing store and mock the enumeration db set with the backing collection 您只需创建一个集合作为后备存储,并使用后备集合模拟枚举数据库集

public class MockDbSet<TEntity> : Mock<DbSet<TEntity>> where TEntity : class {
    public MockDbSet(List<TEntity> dataSource = null) {
        var data = (dataSource ?? new List<TEntity>());
        var queryable = data.AsQueryable();

        this.As<IQueryable<TEntity>>().Setup(e => e.Provider).Returns(queryable.Provider);
        this.As<IQueryable<TEntity>>().Setup(e => e.Expression).Returns(queryable.Expression);
        this.As<IQueryable<TEntity>>().Setup(e => e.ElementType).Returns(queryable.ElementType);
        this.As<IQueryable<TEntity>>().Setup(e => e.GetEnumerator()).Returns(() => queryable.GetEnumerator());
        //Mocking the insertion of entities
        this.Setup(_ => _.Add(It.IsAny<TEntity>())).Returns((TEntity arg) => {
            data.Add(arg);
            return arg;
        });

        //...the same can be done for other members like Remove
    }
}

So now you can use a list to hold the data 所以现在您可以使用列表来保存数据

// ARRANGE
var dataSource = new List<User>(); //<-- this will hold data
var user = new User()
{
    FirstName = "Some",
    LastName = "Guy",
    EmailAddress = "some.guy@mockymoqmoq.com",
};

var mockSet = new MockDbSet<User>(dataSource);
var mockContext = new Mock<WebAPIDbContext>();

mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object);

// ACT
using (var uow = UnitOfWork.Create(mockContext.Object))
{
    uow.UserRepository.Add(user);
    uow.SaveChanges();


    // ASSERT
    mockSet.Verify(u => u.Add(It.IsAny<User>()), Times.Once());
    Assert.IsTrue(dataSource.Contains(user)); //<-- shows mock actually added item
    Assert.IsTrue(uow.UserRepository.Any(u => u == user)); //<-- show you can actually query mock DbSet
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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