.net 核心测试数据库集

.net core testing dbsets

我正在准备我的测试基础设施,但我的测试存储库遇到了一些问题。

真正的版本库访问EntityFramework DbSet,像这样:

public class Repository<T>: IRepository<T> where T : ModelBase
{
    protected ApplicationDbContext db;
    private DbSet<T> dbSet;
    public Repository(ApplicationDbContext db)
    {
        this.db = db;
        dbSet = db.Set<T>();
    }

    public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
    {
        return dbSet.Where(predicate).AsNoTracking();
    }

    ....

我的 TestRepository 使用 List 而不是 DbSets:

public class TestRepository<T> : IRepository<T> where T : ModelBase
{
    private readonly List<T> dbSet;
    protected ApplicationDbContextFake db;        

    public TestRepository(ApplicationDbContextFake db)
    {
        this.db = db;
        this.dbSet = db.Set<T>();
    }

这个db.Set<T>()returns一个列表

测试我的代码时出现问题,有这样的东西:

public async Task DeleteAsync()
{
    var items = repository.Where(....);
    repository.RemoveRange(await items.ToListAsync());

此代码使用 Entity DbSets 运行正常,但在使用我的 TestRepository 测试时抛出异常:

The source IQueryable doesn't implement IAsyncEnumerable. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

有什么解决这个问题的建议吗?

如果您使用的是 EntityFramework Core(而非 EF6)- 您可以使用内存中实现进行测试。

请参阅 Microsoft.EntityFrameworkCore.InMemory 提供商的文档。