【问题标题】:Integration Tests Of generic Repository Using Entity Framework Codefirst and Nunit使用实体框架 Codefirst 和 Nunit 的通用存储库的集成测试
【发布时间】:2012-11-14 17:44:42
【问题描述】:

我使用通用存储库和工作单元模式以及实体框架代码优先构建了一个数据访问层。对存储库进行单元测试对我来说似乎毫无价值,所以我决定创建一些集成测试。为此,我创建了一个专门用于集成测试的项目,并添加了一个自定义数据库初始化程序,它将使用一些测试数据为数据库播种,当然使用不同的连接字符串。

我的问题是:如何以及何时在我的测试代码中初始化数据库?我正在使用 Nunit。另外我想知道 - 由于我的存储库使用通用实现 - 我应该测试我的工作单元中的每个存储库还是只选择一个随机的?

我的代码如下所示:

public interface IRepository<T> where T:class, IEntity
{
    void Add(T entity);
    T GetById(int id);
    IQueryable<T> All();
    IQueryable<T> Where(Expression<Func<T, bool>> filter);
    void Update(T entity);
    void Delete(T entity);
}

 public interface IUnitOfWork : IDisposable
 {
        IRepository<Album> Albums { get; }
        IRepository<Genre> Genres { get; }
        IRepository<Artist> Artists { get; }
        void Commit();
  }  

public class EFRepository<T> : IRepository<T> where T : class,IEntity
{
    private DbContext _context;
    private DbSet<T> _set;

    public EFRepository(IMvcStoreContext context)
    {
        if (context == null)
            throw new NullReferenceException("context is null");

        _context = context as DbContext;

        _set = _context.Set<T>();

    }

    public void Add(T newEntity)
    {
        _set.Add(newEntity);
    }

    public T GetById(int id)
    {
        return _set.Find(id);
    }

    public IQueryable<T> All()
    {
        return _set;
    }

    public IQueryable<T> Where(Expression<Func<T, bool>> filter)
    {
        return _set.Where(filter);
    }

    public void Update(T entity)
    {
        throw new NotImplementedException("method not implemented");
    }

    public void Delete(T entity)
    {
        _set.Remove(entity);
    }
}

【问题讨论】:

    标签: c# entity-framework ef-code-first nunit integration-testing


    【解决方案1】:

    我来这里是为了寻找你第二个问题的答案,所以我没有那个问题的答案。 对于数据库测试,我使用NDBUnit。 我将设置和拆卸放在 TestFixureXXX 方法中,因此每次测试只需为数据库播种一次;这使得慢速测试运行得更快一些。如果您需要有关 NDBUnit 的帮助,请告诉我。

    埃里克

    【讨论】:

    • 谢谢埃里克。它被应用了!
    猜你喜欢
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多