Automapper - AssertConfigurationIsValid调用失败,但映射仍然有效

时间:2014-04-08 19:39:48

标签: c# automapper

不确定这是不是错误,或者我没有正确使用它,但似乎Automapper可以映射属性,即使AssertConfigurationIsValid失败。在以下测试中,即使ShouldMapSourceListAssertConfigurationIsValid失败,ShouldValidateAgainstSourceListOnly也会通过:

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

1 个答案:

答案 0 :(得分:4)

配置验证是为了确保您不会错误地填写目标类型中的内容。由于AutoMapper正在推断您尝试映射的内容,因此测试是关于验证该断言。当然,地图仍然可以正常工作,但您可能会假设目标属性将被映射,而实际上没有匹配的成员。

MemberList枚举是关于要验证的成员列表。默认情况下,它是目标类型,但在某些情况下,我们实际上希望使用源类型作为要检查的成员列表。