.Net core 2.2 中 Linq 语句的模拟单元测试总是 return null

Mock Unit tests for Linq statements in .Net core 2.2 always return null

我知道有人问了很多嘲讽的问题,但 none 和我一起工作。

我正在尝试为我拥有的服务编写单元测试。该服务有以下代码行

    var assignments = await _assignmentRepository.WhereAsync(as => as.DepartmentId == departmentId);

下面是WhereAsync方法的实现:

    public async Task<List<T>> WhereAsync(Expression<Func<T, bool>> expression)
    {
        return await _dbContext.Set<T>().Where(expression).ToListAsync();
    }

这是我的模拟测试语句(listAssignments 是预定义变量):

     _assignmentRepository.Setup(rep => rep.WhereAsync(as => It.IsAny<bool>())).ReturnsAsync(listAssignments);

我知道我们不能模拟 WhereFirstOrDefault 方法,但是没有办法模拟我的网络服务 WhereAsync 方法吗??

正如上面评论中提到的Tseng。我们不模拟 DbContext,我们模拟存储库本身。

所以我使用了InMemoryDatabase测试。向我的内存数据库添加了一些数据,使我的 DbContext return 成为我想要的数据。

        var mapOptions = new DbContextOptionsBuilder<MapViewerContext>()
               .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
               .Options;
        var identityOptions = new DbContextOptionsBuilder<AppIdentityDbContext>()
            .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
            .Options;
        var mapContext = new MapViewerContext(_configuration.Object, mapOptions);
        var appIdentityContext = new AppIdentityDbContext(_configuration.Object, identityOptions);