不知道這是一個錯誤或我不使用它的權利,但似乎Automapper可即使AssertConfigurationIsValid
失敗映射屬性。在下面的測試中,ShouldMapSourceList
會通過,即使在AssertConfigurationIsValid
失敗ShouldValidateAgainstSourceListOnly
:Automapper - AssertConfigurationIsValid調用失敗,但仍然映射工作
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
什麼是'MemberList.Source'? – Kehlan
您可以傳遞給'CreateMap'的枚舉之一。本質上它告訴Automapper檢查所有源成員是否被映射。默認是'MemberList.Destination'。 – Mrchief
我對'AssertConfigurationIsValid'的理解是,它檢查目標類型中缺失的成員。這與根本不能映射這兩種類型是不一樣的。 AutoMapper仍然會盡力將運行時的類型映射到彼此儘可能好的位置。換句話說,僅僅因爲'AssertConfigurationIsValid'失敗,這並不意味着AutoMapper將無法映射類型。 –