不知道这是一个错误还是我没有正确使用它,但是即使AssertConfigurationIsValid失败,似乎Automapper仍可以映射属性.在以下测试中,即使AssertConfigurationIsValid在ShouldValidateAgainstSourceListOnly中失败,ShouldMapSourceList也将通过:
using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AutoMapperTests
{
[TestClass]
public class CreateMapTests
{
private class A
{
public string PropID { get; set; }
public string PropB { get; set; }
}
private class B
{
public string PropId { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
}
internal class CreateMapTestProfile : Profile
{
protected override void Configure()
{
// will complain about Unmapped member PropC when AssertConfigurationIsValid is called.
CreateMap<A, B>();
}
}
internal class CreateMapTestWithSourceMemberListProfile : Profile
{
protected override void Configure()
{
// will complain about Unmapped member PropID when AssertConfigurationIsValid is called.
CreateMap<A, B>(MemberList.Source);
}
}
[TestMethod]
public void ShouldMapSourceList()
{
Mapper.AddProfile<CreateMapTestWithSourceMemberListProfile>();
//Mapper.AssertConfigurationIsValid();
var a = new A
{
PropID = "someId",
PropB = "random",
};
var actual = Mapper.Map<B>(a);
Assert.AreEqual("someId", actual.PropId);
}
[TestMethod]
public void ShouldValidateAgainstSourceListOnly()
{
Mapper.AddProfile<CreateMapTestWithSourceMemberListProfile>();
Mapper.AssertConfigurationIsValid();
// if we got here without exceptions, it means we're good!
Assert.IsTrue(true);
}
}
}
如果配置无效,映射是否应该失败?或者,如果配置有效,为什么AssertConfigurationIsValid失败?
在这里测试项目:https://github.com/mrchief/AutoMapperTests/blob/master/CreateMapTests.cs
解决方法:
配置验证是关于确保您不会拼写目标类型中的某些内容.由于AutoMapper会推断您要映射的内容,因此测试将验证该断言.该地图当然仍然可以工作,但是您可能会假设实际上没有匹配的成员时将映射目标属性.
MemberList枚举与要验证的成员列表有关.默认情况下,它是目标类型,但是在某些情况下,我们实际上想使用源类型作为要检查的成员列表.