gpt4 book ai didi

c# - Automapper 实例配置尚未在 xUnit 测试中初始化

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:15 24 4
gpt4 key购买 nike

我正在使用 xUnit 在 Web API Asp.Net Core 上编写一些单元测试,并且正在测试我的服务。

我创建了一个构建器类,它创建映射器实例,以便在构造函数中创建需要 IMapper 的类。

public IMapper Mapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<CustomerRoleProfile>();
cfg.AddProfile<LicenseProfile>();
cfg.AddProfile<TaxExemptionProfile>();
cfg.AddProfile<BankProfile>();
cfg.AddProfile<AddressProfile>();
cfg.AddProfile<CustomerDetailsProfile>();
cfg.AddProfile<CustomerProfile>();
});
return config.CreateMapper();
}

但是每次我使用映射器实例时都会抛出这个错误

System.InvalidOperationException: Mapper not initialized

如果我尝试断言配置,所有测试都会失败

        config.AssertConfigurationIsValid();

但如果我尝试使用具有相同配置的静态实例,它不会失败,但一些测试会失败,因为如果我有更多测试类,Automapper 已经初始化。

public IMapper Mapper() 
{
AutoMapper.Mapper.Reset();
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.AddProfile(new CustomerRoleProfile());
cfg.AddProfile(new LicenseProfile());
cfg.AddProfile(new TaxExemptionProfile());
cfg.AddProfile(new BankProfile());
cfg.AddProfile(new AddressProfile());
cfg.AddProfile(new CustomerDetailsProfile());
cfg.AddProfile(new CustomerProfile());
});
return Automapper.Mapper.Configuration.CreateMapper();
}

使用静态Automapper,所有测试来自一个类,例如,这个测试是成功的

[Fact]
public async Task UpdateOrInsertCustomer()
{
var customer = new CustomerCreateDto() { CustomerId = 1, StoreId = 1, CardTypeCode = "GO", InvoiceTypeCode = "PRO", SelfScanningAllowed = true, TradeId = 12345, CountryCode = "ROU" };
var result = await _customerService.UpdateOrInsert(customer);
result.Should().BeTrue();
}

另一个类的一些测试失败了,例如这个

[Theory]
[InlineData(1, 1, null)]
public async Task GeValidCustomerDetails(int customerId, int storeId, int? cardHolderId)
{
var result = await _detailsService.GetAsync(customerId, storeId, cardHolderId);
if (!cardHolderId.HasValue)
result.Should().NotBeNull().And.Subject.Should().BeOfType<OrganizationDto>();
else
result.Should().NotBeNull().And.Subject.Should().BeOfType<PersonDto>()
.And.Subject.As<PersonDto>().CardHolderId.Should().Be(cardHolderId.Value);
result.CustomerId.Should().Be(customerId);
result.StoreId.Should().Be(storeId);
}

最佳答案

作为一种变通方法,我使用带有静态包装器和锁的静态实例来避免竞争条件,它适用于所有单元测试。我不知道为什么映射器配置实例不起作用。

关于c# - Automapper 实例配置尚未在 xUnit 测试中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com