[c#]EF 通用存储库和工作单位-单元测试使用最小起订量

发布时间: 2017/2/25 3:27:42
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

在我的应用程序,我有以下 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 的指导):

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

我的控制器使用 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
}

这所有的作品就好。现在我想要一些单元测试。想要假 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() 方法 (值不能为空)。调试表明在构造函数中出现的问题︰

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

有没有任何方法能修好?

解决方法 1:

这是因为在任何地方你 FakeUnitOfWork 代码做你安装 Set DbContext 为你戏弄的 DbSet 方法。下面给你InitFakeDbContext

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

当使用最小起订量您想要安装程序将使用您在测试中的成员,否则你会得到一个异常。

官方微信
官方QQ群
31647020