【问题标题】:Automapper instance configuration has not been initialized in xUnit testAutomapper 实例配置尚未在 xUnit 测试中初始化
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 你应该切换到基于实例的 API。
    • 当我尝试使用映射器配置实例时,断言配置有效失败。仅在单元测试中。我只是在 xUnit 项目中使用这个静态实例
    • 你不应该使用任何静态的东西。检查the docs
    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2017-01-27
    • 2021-10-25
    • 2017-09-23
    • 1970-01-01
    相关资源
    最近更新 更多