【发布时间】:2018-08-02 19:44:24
【问题描述】:
我正在 Web API Asp.Net Core 上使用 xUnit 编写一些单元测试,并且正在测试我的服务。
我已经创建了一个构建器类来创建映射器实例,以便在构造器中创建需要 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# asp.net automapper xunit