c# - .Net Core 单元测试错误 - 源 IQueryable 未实现 IAsyncEnumerable<...>

标签 c# unit-testing automapper moq .net-core-3.1

我有一行代码在单元测试中失败,但在开发和生产中运行得很好。

var result = await _mapper.ProjectTo<GetApplicationsResponse.Application>(pipelineContext.Query).ToListAsync(cancellationToken);

pipelineContext.Query类型为IQueryable .

我尝试进行的测试如下

[Fact]
public async Task Handle_Success_Returns_GetApplicationsResponse()
{
    //Arrange
    var sut = CreateSut();

    _pipelineSteps
        .Setup(steps => steps.GetEnumerator())
        .Returns(() => new List<IPipelineStep<GetApplicationsContext>>
        {
            Mock.Of<IPipelineStep<GetApplicationsContext>>()
        }.GetEnumerator());

    _mapper.Setup(x => x.ConfigurationProvider)
        .Returns(
            () => new MapperConfiguration(
                cfg =>
                {
                    cfg.CreateMap<Entities.ApplicationsAggregate.Application, GetApplicationsResponse.Application>();
                    cfg.CreateMap<Entities.ApplicationsAggregate.SiteLocation, GetApplicationsResponse.SiteLocation>();
                    cfg.CreateMap<Entities.ApplicationsAggregate.SiteAddress, GetApplicationsResponse.SiteAddress>();
                }));

    //Act
    var result = await sut.Handle(new GetApplicationsRequest(), default);
    
    //Assert
    result.Should().BeOfType<GetApplicationsResponse>();
    _pipelineSteps.Verify(steps => steps.GetEnumerator(), Times.Once);
}

我在这方面的局限性是我无法从 _projectTo<...> 进行更改因为这是新的方法\工作标准。

因此,我将不胜感激任何能够解决此错误的帮助

System.InvalidOperationException : The source IQueryable doesn't implement IAsyncEnumerable<TQ.Applications.Application.Queries.GetApplications.GetApplicationsResponse+Application>. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

---- 编辑 ---

忘记之前提到测试正在使用内存数据库

最佳答案

问题是 ToListAsync 需要一个实现 IAsyncEnumerable 的序列,但 ProjectTo 没有给它一个序列。

您正在使用 EntityFrameworkCore 内存提供程序,我假设您将其注入(inject)到 SUT 中,并且在失败时会引用它。这是主要问题,因为内存提供程序不提供实现 IAsyncEnumerable 的序列。 ProjectTo 最终向 ToListAsync 提供了一个 IQueryable ,但这是行不通的。

至于如何解决,有以下几种方法。

  1. 懒惰/正确的方法:使用更好的 DbContext。

以下 LINQPad 示例使用 EntityFrameworkCore.Testing.Moq创建一个可注入(inject)的 DbContext 来生成 IAsyncEnumerable 序列:

void Main()
{
    var fixture = new Fixture();

    var dataEntites = fixture.CreateMany<DataEntity>();
    var expectedResult = dataEntites.Select(x => new BusinessEntity() { id = x.Id, code = x.Code });

    var mapper = new Mapper(new MapperConfiguration(x => x.AddProfile(new MappingProfile())));
    var pipelineContext = Create.MockedDbContextFor<PipelineContext>();
    pipelineContext.Entities.AddRangeToReadOnlySource(dataEntites);

    var sut = new SUT(mapper, pipelineContext);

    var actualResult = sut.Handle().Result;

    var compareLogic = new CompareLogic();
    compareLogic.Config.IgnoreObjectTypes = true;
    compareLogic.Config.IgnoreCollectionOrder = true;
    var comparisonResult = compareLogic.Compare(expectedResult, actualResult);
    Console.WriteLine($"Are the sequences equivalent: {comparisonResult.AreEqual}");
    Console.WriteLine(expectedResult);
    Console.WriteLine(actualResult);
}

public class SUT
{
    IMapper _mapper;
    PipelineContext _pipelineContext;

    public SUT(IMapper mapper, PipelineContext pipelineContext)
    {
        _pipelineContext = pipelineContext;
        _mapper = mapper;
    }

    public async Task<List<BusinessEntity>> Handle()
    {
        return await _mapper.ProjectTo<BusinessEntity>(_pipelineContext.Entities).ToListAsync();
    }
}

public class PipelineContext : DbContext
{
    public PipelineContext(DbContextOptions<PipelineContext> options) : base(options) { }

    public virtual DbSet<DataEntity> Entities { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<DataEntity>().HasNoKey().ToView(nameof(DataEntity));
    }
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<DataEntity, BusinessEntity>()
        .ForMember(d => d.id, o => o.MapFrom(s => s.Id))
        .ForMember(d => d.code, o => o.MapFrom(s => s.Code))
        .ReverseMap();
    }
}

public class DataEntity
{
    public Guid Id { get; set; }

    public string Code { get; set; }
}

public class BusinessEntity
{
    public Guid id { get; set; }

    public string code { get; set; }
}

这将返回:

enter image description here

显然,在没有最小可重现示例的情况下,我已经简化了这一点,但这不应该改变方法。我假设该集合是基于属性名称(查询)的只读集合,因此使用 AddToReadOnlySource 进行排列。如果它不是只读的,您可以使用 AddRange 代替。

  • 模拟映射器。
  • 我大部分时间都根据 JBogard 对这个主题的评论使用真正的映射器。然而,由于您似乎愿意 mock 它,因此您可以简单地模拟 ProjectTo 调用以返回所需的 IAsyncEnumerable 序列:

    void Main()
    {
        var fixture = new Fixture();
        
        var dataEntites = new AsyncEnumerable<DataEntity>(fixture.CreateMany<DataEntity>());
        var expectedResult = new AsyncEnumerable<BusinessEntity>(dataEntites.Select(x => new BusinessEntity() { id = x.Id, code = x.Code }));
    
        var mapperMock = new Mock<IMapper>();
        mapperMock.Setup(x => x.ProjectTo<BusinessEntity>(It.IsAny<IQueryable<DataEntity>>(), It.IsAny<object>())).Returns(expectedResult);
        var mapper = mapperMock.Object;
    
        var sut = new SUT(mapper);
    
        var actualResult = sut.Handle(dataEntites).Result;
    
        var compareLogic = new CompareLogic();
        compareLogic.Config.IgnoreObjectTypes = true;
        compareLogic.Config.IgnoreCollectionOrder = true;
        var comparisonResult = compareLogic.Compare(expectedResult, actualResult);
        Console.WriteLine($"Are the sequences equivalent: {comparisonResult.AreEqual}");
        Console.WriteLine(expectedResult);
        Console.WriteLine(actualResult);
    }
    
    public class SUT
    {
        IMapper _mapper;
    
        public SUT(IMapper mapper)
        {
            _mapper = mapper;
        }
    
        public async Task<List<BusinessEntity>> Handle(IQueryable<DataEntity> entities)
        {
            return await _mapper.ProjectTo<BusinessEntity>(entities).ToListAsync();
        }
    }
    
    public class DataEntity
    {
        public Guid Id { get; set; }
    
        public string Code { get; set; }
    }
    
    public class BusinessEntity
    {
        public Guid id { get; set; }
    
        public string code { get; set; }
    }
    

    结果:

    enter image description here

    这使用 AsyncEnumerable来自 EntityFrameworkCore.Testing 的类(class)如果您愿意,您可以按原样使用它,也可以将其作为您自己实现的基础。

    关于c# - .Net Core 单元测试错误 - 源 IQueryable 未实现 IAsyncEnumerable<...>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63903685/

    相关文章:

    c# - 使用utf16编码将字符串写入流

    javascript - 是否可以在同一模块中监视(开 Jest )多个方法?

    c# - 使用 Automapper 的自定义映射,其中目标字段是源中两个字段的串联

    c# - Kinect V2 - 如何将 kinect v2 坐标转换为现实生活中的测量值?

    c# - 如何允许对 gridview 进行排序?

    c# - 确保泛型集合包含派生自两个基础对象的对象

    php - 在 CakePHP 单元测试中模拟 ajax 请求

    python - Python Eve Web 服务的单元测试用例

    c# - 将 Automapper 与 ASP.NET Core 结合使用

    c# - 自动映射器将深对象自动映射到平面对象并返回