Unit testing Net core 2.2中Linq语句的模拟单元测试总是返回null

Unit testing Net core 2.2中Linq语句的模拟单元测试总是返回null,unit-testing,asp.net-core,mocking,asp.net-core-2.2,Unit Testing,Asp.net Core,Mocking,Asp.net Core 2.2,我知道有人问了很多嘲弄性的问题,但没有一个对我有用 我正在尝试为我拥有的服务编写一个单元测试。该服务具有以下代码行 var assignments = await _assignmentRepository.WhereAsync(as => as.DepartmentId == departmentId); 下面是wheresync方法的实现: public async Task<List<T>> WhereAsync(Expression<

我知道有人问了很多嘲弄性的问题,但没有一个对我有用

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

    var assignments = await _assignmentRepository.WhereAsync(as => as.DepartmentId == departmentId);
下面是
wheresync
方法的实现:

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

我知道我们不能模仿
Where
FirstOrDefault
方法,但是没有办法模仿我的web服务
wheresync
方法???

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

因此,我使用内存数据库中的
进行测试。在内存数据库中添加了一些数据,使我的
DbContext
返回所需的数据

        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);
var-mapOptions=new-DbContextOptionsBuilder()
.UseInMemoryDatabase(数据库名称:Guid.NewGuid().ToString())
.选择;
var identityOptions=new DbContextOptionsBuilder()
.UseInMemoryDatabase(数据库名称:Guid.NewGuid().ToString())
.选择;
var mapContext=新的MapViewerContext(_configuration.Object,mapOptions);
var appIdentityContext=新的AppIdentityDbContext(_configuration.Object,identityOptions);

最大的问题是:您真正想要测试什么?通常您模拟存储库,而不是DbContext,因此存储库的实现根本不重要,您模拟存储库接口。单元测试EF核心是毫无意义的。您可以单元测试您的代码,而不是其他代码我正在测试服务。服务接收部门Id作为参数,并返回此部门中的工作分配。所以我正在执行一个
wheresync
在分配存储库中实现,其中
assignment.departmentId
equal
Id
由参数发送。这不是单元测试。在单元测试中,您使用模拟来替换对存储库实现的调用,该模拟将您希望/需要的结果返回到依赖于存储库的对象逻辑
        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);