使用Automapper进行对象映射非常有用,但为了确保映射配置正确,需要编写一个单元测试来对其进行验证。以下是一个示例单元测试代码:
[TestClass]
public class AutoMapperTests
{
[TestMethod]
public void TestMapping()
{
var config = new MapperConfiguration(cfg => {
cfg.AddProfile(new MappingProfile());
});
var mapper = config.CreateMapper();
var source = new SourceModel { Id = 1, Name = "Test" };
var dest = mapper.Map(source);
Assert.AreEqual(source.Id, dest.Id);
Assert.AreEqual(source.Name, dest.Name);
}
}
public class SourceModel
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DestModel
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap();
}
}
这个单元测试创建了一个Automapper配置并使用它将源模型映射到目标模型。在测试中可以验证源和目标模型的属性是否正确地映射。如果在映射配置中存在任何错误,测试将失败并提供有关哪个属性映射失败的信息。