gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:38:17 32 4
gpt4 key购买 nike

我得到一个

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

尝试使用 XUnit 测试框架在我的单元测试类中注册 AutoMapper 时出错。

我有一个包含 3 层的应用程序(演示 - 业务 - 数据)。业务层和表示层都有自己的 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
...
}
}

关于c# - 在 .Net Core 2.1 的 XUnit 单元测试中注册 AutoMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53973952/

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