c# – 在.Net Core 2.1中的XUnit单元测试中注册AutoMapper

我得到了一个

“System.InvalidOperationException : Mapper already initialized. You must call Initialize once per application domain/process.”

尝试使用XUnit测试框架在我的Unit测试类中注册AutoMapper时出错.

我有一个3层的应用程序(演示 – 业务 – 数据). Business层和Presentation层都有自己的AutoMapper Profile类,这些类在Startup上调用的类中注册.

商业:

public class AutoMapperBusinessProfile : Profile
{
    public AutoMapperBusinessProfile()
    {
        CreateMap<WeatherEntity, WeatherModel>()
            .ForMember(x => x.Location, y => y.MapFrom(z => z.Name))
            .ForMember(x => x.Temperature, y => y.MapFrom(z => z.Main.Temp))

            // Here be mappings
            ...
    }
}

介绍:

public class AutoMapperPresentationProfile : Profile
{
    public void RegisterMaps()
    {
        CreateMap<WeatherModel, MainViewModel>()
            .ForMember(dest => dest.TemperatureUom, x => x.MapFrom(src => src.TemperatureUom.ToString()));

        CreateMap<TrafficModel, MainViewModel>()
            .ConvertUsing<TrafficModelConverter>();

        // More mappings
        ...
    }
}

启动:

public static class AutoMapperConfiguration
{
    public static void RegisterAutoMapper()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AutoMapperBusinessProfile>();
            cfg.AddProfile<AutoMapperPresentationProfile>();
        });
    }
}

我可以正常运行应用程序,所有映射都是正确的.然而;当我尝试在我的代码上运行单元测试时,我首先在映射部分上得到了空引用错误.添加代码以在构造函数中重置和实例化Profile,允许单个单元测试类正确运行.

public WeatherBusinessTests()
{
    _service = new WeatherService();

    // Initialize AutoMapper in test class
    Mapper.Reset();
    Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperBusinessProfile>());
}

但是,当使用Mapper.Reset()方法运行多个测试类时,我收到以下错误:

System.InvalidOperationException : Mapper already initialized. You must call Initialize once per application domain/process.

运行单个测试类会产生预期结果.如何正确注册Automapper,以便我的所有测试可以并排运行并获得所需的映射信息?

// Calling AutoMapper in code
public TModel MapFromEntity(TEntity entity)
{
   var model = Mapper.Map<TModel>(entity);
   return model;
}

最佳答案 我相信这部分有问题,你使用RegisterMaps方法而不是构造函数AutoMapperPresentationProfile()

public class AutoMapperPresentationProfile : Profile
{
    public void RegisterMaps()
    {
        CreateMap<WeatherModel, MainViewModel>()
            .ForMember(dest => dest.TemperatureUom, x => x.MapFrom(src => src.TemperatureUom.ToString()));

        CreateMap<TrafficModel, MainViewModel>()
            .ConvertUsing<TrafficModelConverter>();

        // More mappings
        ...
    }
}

将其转换为

public class AutoMapperPresentationProfile : Profile
{
    public void AutoMapperPresentationProfile ()
    {
        CreateMap<WeatherModel, MainViewModel>()
            .ForMember(dest => dest.TemperatureUom, x => x.MapFrom(src => src.TemperatureUom.ToString()));

        CreateMap<TrafficModel, MainViewModel>()
            .ConvertUsing<TrafficModelConverter>();

        // More mappings
        ...
    }
}
点赞