【问题标题】:.net core testing dbsets.net 核心测试数据库集
【发布时间】:2017-03-30 20:32:32
【问题描述】:

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

真正的仓库访问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 而不是 DbSet:

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&lt;T&gt;() 返回一个列表

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

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

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

源 IQueryable 未实现 IAsyncEnumerable。只有实现 IAsyncEnumerable 的源才能用于实体框架异步操作。

有解决此问题的建议吗?

【问题讨论】:

    标签: c# asp.net-core xunit.net


    【解决方案1】:

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

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

    【讨论】:

    • 这更像是一种解决方法,而不是正确回答错误发生的原因,但我同意这个意图。
    • 完美。作为奖励,我删除了 TestRepository。
    猜你喜欢
    • 2011-06-24
    • 2017-04-24
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2020-10-16
    • 2017-07-13
    相关资源
    最近更新 更多