我如何对使用注入服务的配置文件进行单元AfterMap测试IMappingAction。
映射配置文件.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?