c# - EF 通用存储库和工作单元 - 使用 Moq 进行单元测试

标签 c# asp.net entity-framework unit-testing moq

在我的应用程序中,我有以下 DbContext:

public class LibraryContext : DbContext
{
    public virtual DbSet<LibraryUser> LibraryUsers { get; set; }
    public virtual DbSet<BookCollection> BookCollections { get; set; }
    public virtual DbSet<Book> LibraryBooks { get; set; }

    public LibraryContext() : base("ExternalDB")
    {    
    }
}

数据库资源由工作单元和通用存储库管理(基于 ASP.NET's guidance ):

public class UnitOfWork : IUnitOfWork, IDisposable
{
    private LibraryContext context = new LibraryContext();
    private GenericRepository<BookCollection> collectionRepository;
    private GenericRepository<LibraryUser> userRepository;
    private GenericRepository<Book> bookRepository;

    public GenericRepository<BookCollection> BookCollectionRepository
    {
        get
        {

            if (this.collectionRepository == null)
            {
                this.collectionRepository = new GenericRepository<BookCollection>(context);
            }
            return collectionRepository;
        }
    }

    public GenericRepository<LibraryUser> LibraryUserRepository
    {
        get
        {

            if (this.userRepository == null)
            {
                this.userRepository = new GenericRepository<LibraryUser>(context);
            }
            return userRepository;
        }
    }

    public GenericRepository<Book> BookRepository
    {
        get
        {

            if (this.bookRepository == null)
            {
                this.bookRepository = new GenericRepository<Book>(context);
            }
            return bookRepository;
        }
    }

    public void Save()
    {
        context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

存储库:

public class GenericRepository<TEntity> where TEntity : class
{
    internal LibraryContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(LibraryContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetById(object id)
    {
        return dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
}

我的 Controller 通过以下方式使用 UoW:

public class HomeController : Controller
{
    IUnitOfWork uow;

    public HomeController() : this (new UnitOfWork())
    {
    }

    public HomeController(IUnitOfWork uow)
    {
        this.uow = uow;
    }

    public ActionResult Index()
    {
        if (Request.IsAuthenticated)
        {
            var books = uow.BookRepository.Get(filter:
                b => b.UserId.HasValue, orderBy:
                q => q.OrderBy(b => b.ReturnDate))
                .Take(50);
                //rest of the code
        }
        //rest of the code
    } 
//rest of the code
}

这一切都运行得很好。现在我想做一些单元测试。尝试使用 Moq 制作一个假的 LibraryUsers DbSet:

class FakeUnitOfWork : IUnitOfWork
{

    Mock<LibraryContext> _mockContext;

    public FakeUnitOfWork()
    {
        InitFakeDbContext();
    }

    public GenericRepository<LibraryUser> LibraryUserRepository
    {
        get
        {
            return new GenericRepository<LibraryUser>(_mockContext.Object);
        }
    }

    public void Save()
    {
        throw new NotImplementedException();
    }

    public void InitFakeDbContext()
    {
        var data = FakeUsers.GetUsers(); // IQueryable<LibraryUser> data

        var mockSet = new Mock<DbSet<LibraryUser>>();
        mockSet.As<IQueryable<LibraryUser>>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<LibraryUser>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<LibraryUser>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<LibraryUser>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        _mockContext = new Mock<LibraryContext>();
        _mockContext.Setup(c => c.LibraryUsers).Returns(mockSet.Object);
    }
    // rest of the code
}

但在 Generic RepositoryGet() 方法上测试实际上失败了(Value 不能为 null)。调试发现问题出现在构造函数中:

public GenericRepository(LibraryContext context)
{
    this.context = context;
    this.dbSet = context.Set<TEntity>(); // dbSet is actually null
}

有什么办法可以解决吗?

最佳答案

这是因为在您的 FakeUnitOfWork 代码中,您没有在 DbContext 上为模拟的 DbSet 设置 Set 方法。将以下内容添加到您的 InitFakeDbContext

_mockContext.Setup(c => c.Set<LibraryUser>()).Returns(mockSet.Object);

使用 Moq 时,您需要设置将在测试中使用的成员,否则会出现异常。

关于c# - EF 通用存储库和工作单元 - 使用 Moq 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660259/

相关文章:

asp.net-mvc - ASP.net MVC 4,连接字符串

c# - 当来自另一个线程的事件更改属性时, View 不更新

c# - Winforms 应用程序停止绘图但仍对事件有反应

c# - 检查数字的小数点和总长度

asp.net - Sitecore 获取渲染的 Html

c# - 尝试在 EF Core 中使用 `ThenInclude` 时出现异常

c# - 将 MySQL PASSWORD() 与 Entity Framework 结合使用

c# - DocumentDB 替换文档失败

javascript - 为什么将 string 转换为 int 时不能正确工作(parseInt)?

asp.net - AJAX 级联下拉菜单没有更新面板?