[英]Register AutoMapper in XUnit Unit Tests in .Net Core 2.1
我正在
“ System.InvalidOperationException:映射器已经初始化。您必须为每个应用程序域/进程调用一次Initialize。”
尝试使用XUnit测试框架在我的单元测试类中注册AutoMapper时发生错误。
我有一个包含3层(演示文稿-业务-数据)的应用程序。 业务层和表示层都具有自己的AutoMapper配置文件类,这些类在“启动”类中注册。
商业:
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:映射器已经初始化。 您必须为每个应用程序域/进程调用一次Initialize。
运行单个测试类会产生预期的结果。 如何正确注册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
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.