简体   繁体   English

Moq 测试实体框架

[英]Moq testing Entity Framework

I am newbie to both Entity Framework and Moq testing .我是Entity FrameworkMoq testing的新手。

Below is my EF code :下面是我的EF code

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{

    protected readonly DbContext Context;
    public Repository(DbContext context)
    {
        Context = context;
    }

    public TEntity Get(int id)
    {
      
        return Context.Set<TEntity>().Find(id);
    }

    public IEnumerable<TEntity> GetAll()
    {
       
        return Context.Set<TEntity>().ToList();
    }

    public void Add(TEntity entity)
    {
        Context.Set<TEntity>().Add(entity);
    }

    public void Remove(TEntity entity)
    {
        Context.Set<TEntity>().Remove(entity);
    }

}


public interface IRepository<TEntity> where TEntity : class
{

    TEntity Get(int id);
    IEnumerable<TEntity> GetAll();


    void Add(TEntity entity);

    void Remove(TEntity entity);

}


public interface IUnitOfWork : IDisposable
{

    int Complete();
}


public class UnitOfWork : IUnitOfWork
{


    private readonly EF_SalesOrdersDBContext _context;

    public CustomersRepository customersRepository { get; set; }

    public UnitOfWork(EF_SalesOrdersDBContext context)
    {
        _context = context;
        customersRepository = new CustomersRepository(_context);
    }



    public int Complete()
    {
        return _context.SaveChanges();
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}

public class CustomersRepository : Repository<Customer>
{
    public CustomersRepository(EF_SalesOrdersDBContext context)
        :base(context)
    {
            
    }



}

Code below in program.cs which works. program.cs中的以下代码有效。

   UnitOfWork unitOfWork = new UnitOfWork(new EF_SalesOrdersDBContext());
        unitOfWork.customersRepository.Add(new Customer { CompanyName = "test2", FirstName = "John", LastName = "Barnes", AddressLine1 = "11 lfc", City = "Liverpool", County = "LFC", Phone = "444" });         
        unitOfWork.Complete();

I would like test using Moq .我想使用Moq进行测试。

This is what I have tried:这是我尝试过的:

 [TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
  
        var mockSet = new Mock<DbSet<Customer>>();

        var mockContext = new Mock<EF_SalesOrdersDBContext>();
        mockContext.Setup(m => m.Customers).Returns(mockSet.Object);


        var service = new CustomersRepository(mockContext.Object);

   

        service.Add(new Customer { CompanyName = "test2", FirstName = "John", LastName = "Barnes", AddressLine1 = "11 lfc", City = "Liverpool", County = "LFC", Phone = "444" });

        mockSet.Verify(m => m.Add(It.IsAny<Customer>()), Times.Once());
        mockContext.Verify(m => m.SaveChanges(), Times.Once());


    }

}

I get the error:我得到错误:

Message: Test method UnitTestProject1.UnitTest1.TestMethod1 threw exception: System.NullReferenceException: Object reference not set to an instance of an object.消息:测试方法 UnitTestProject1.UnitTest1.TestMethod1 抛出异常:System.NullReferenceException:Object 引用未设置为 object 的实例。 Stack Trace: Repository`1.Add(TEntity entity) line 34 UnitTest1.TestMethod1() line 26堆栈跟踪:存储库`1.Add(TEntity entity) 第 34 行 UnitTest1.TestMethod1() 第 26 行

Mocking db context is a bad idea - you can simply use an in memory context and avoid mocking everything. Mocking 数据库上下文是一个坏主意 - 您可以简单地在 memory 上下文中使用并避免 mocking 一切。 It will work just like the real database.它将像真正的数据库一样工作。

See these suggestions from Microsoft: https://docs.microsoft.com/en-us/ef/core/testing/请参阅 Microsoft 的这些建议: https://docs.microsoft.com/en-us/ef/core/testing/

This question has some answers that show how to make the in memory context: Unit testing with EF Core and in memory database这个问题有一些答案,显示如何在 memory 上下文中制作: Unit testing with EF Core and in memory database

A key reason for implementing a repository pattern with Entity Framework is to enable unit testing.使用实体框架实现存储库模式的一个关键原因是启用单元测试。 The Repository becomes the abstraction point for the unit tests.存储库成为单元测试的抽象点。 Basically think of it this way:基本上是这样想的:

  • You trust that EF is written and tested correctly to guarantee you'll get what you're supposed to get.您相信 EF 的编写和测试是正确的,以保证您会得到您应该得到的东西。
  • The repository's purpose is solely to serve as a relay, containing no high-level business logic.存储库的目的仅仅是充当中继,不包含高级业务逻辑。
  • Any low-level rules that a repository may enforce that are dependent on Data State will be covered by integration tests.存储库可能强制执行的依赖于数据 State 的任何低级规则都将包含在集成测试中。 These tests would be run using either a known-state snapshot database or in-memory database.这些测试将使用已知状态的快照数据库或内存数据库运行。

So where your main business logic should be residing in your Services / Controllers, that is where your unit tests would be targeting.因此,您的主要业务逻辑应该驻留在您的服务/控制器中,这就是您的单元测试的目标。 The Mocks are made for your Repositories, not EF DbContexts/DbSets. Mocks 是为您的存储库制作的,而不是 EF DbContexts/DbSets。

So for example, given your structure I would have a Mock of the UnitOfWork which asserts whether any Complete() call is made (or not), then mock out the Repository for expected methods to return a known state.因此,例如,给定您的结构,我将有一个 UnitOfWork 模拟,它断言是否进行了(或不)任何Complete()调用,然后模拟存储库以获取预期的方法以返回已知的 state。

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

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