不确定这是一个错误还是我没有正确使用它,但Automapper似乎可以映射属性,即使AssertConfigurationIsValid
失败。在以下测试中,即使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枚举是关于要验证的成员列表。默认情况下,它是目标类型,但在某些情况下,我们实际上希望使用源类型作为要检查的成员列表。