我有一行代码在单元测试中失败,但在开发和生产中运行得很好。
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
至于如何解决,有以下几种方法。
- 懒惰/正确的方法:使用更好的 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; }
}
这将返回:
显然,在没有最小可重现示例的情况下,我已经简化了这一点,但这不应该改变方法。我假设该集合是基于属性名称(查询)的只读集合,因此使用 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; }
}
结果:
这使用 AsyncEnumerable来自 EntityFrameworkCore.Testing 的类(class)如果您愿意,您可以按原样使用它,也可以将其作为您自己实现的基础。
关于c# - .Net Core 单元测试错误 - 源 IQueryable 未实现 IAsyncEnumerable<...>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63903685/