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

本文关键字:有效 映射 调用 失败 Automapper-AssertConfigurationIsValid | 更新日期: 2023-09-27 17:57:38

不确定这是一个错误还是我没有正确使用它,但Automapper似乎可以映射属性,即使AssertConfigurationIsValid失败。在以下测试中,即使AssertConfigurationIsValidShouldValidateAgainstSourceListOnly:中失败,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-AssertConfigurationIsValid调用失败,但映射仍然有效

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

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