我如何对使用
AfterMap
和具有注入服务的 IMappingAction
的配置文件进行单元测试。
MappingProfile.cs
public MappingProfile()
{
CreateMap<string, string>()
.ConvertUsing<Core.Converter.TrimStringValueConverter>();
CreateMap<TestModel, TestEntity>(
.AfterMap<AfterMapAction>();
}
AfterMapAction.cs
public class AfterMapAction: IMappingAction<TestModel, TestEntity>
{
private readonly IAfterMapService _afterMapService ;
public AfterMapAction(IAfterMapService aftermapService)
{
_afterMapService = afterMapService ?? throw new ArgumentNullException(nameof(afterMapService));
}
public void Process(TestModel, TestEntity destination, ResolutionContext context)
{
var somevalue = _afterMapService.DoAction(source);
...
}
}
测试.cs
[TestMethod]
public void AutoMapperTest()
{
// Arrange
var model = new TestModel { Id = "4711" , Name = "Test" };
var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.AddProfile<MappingProfile>();
}));
// Act
var mappedObject = mapper.Map<Entity>(model);
...
}
当我运行此测试时,出现以下异常:
System.MissingMethodException:“没有为类型‘AfterMapAction’定义无参数构造函数。
使用
cfg.ConstructServicesUsing
不起作用。它总是以 InvalidCastException 结束。
如何安排单元测试,以便AutoMapper可以实例化
AfterMapAction
?
我可以通过使用单元测试中的
IServiceCollection
来解决这个问题。
// Arrange
var services = new ServiceCollection();
services.AddSingleton<AfterMapAction>();
services.AddSingleton<IAfterMapService, AfterMapService>();
services.AddAutoMapper(cfg => cfg.AddProfile<MappingProfile>());
var serviceProvider = services.BuildServiceProvider();
var mapper = serviceProvider.GetService<IMapper>();
// Act
另一种变体是使用 CreateMapper 函数来定义自定义 IMappingAction。
// Arrange
var afterMapAction = new AfterMapAction(any_dependency_here);
var mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingProfile());
});
_mapper = mapperConfiguration.CreateMapper(x =>
{
if (x == typeof(AfterMapAction))
{
return afterMapAction;
}
return null;
});