.NET 5 Class 库 xUnit 测试在比较来自 AutoMapper 的对象时失败

.NET 5 Class Library xUnit Tests failing when comparing objects from AutoMapper

我目前正在处理没有启动方法的 .NET 5 class 库项目。

我试图实现的想法是,开发人员可以利用该库并传入一个对象。该对象将 运行 通过该方法,AutoMapper 将获取与 FirstDTO 中的属性对齐的属性,然后 return 一个可在任何其他项目中使用的 DTO。

我对 AutoMapper 位比较陌生,在这里找到了这篇文章:How to configure Auto mapper in class library project?

我喜欢这种方法并利用它来将动态对象映射到 DTO:

Configuration.cs

public static class Configuration
    {
        private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
                cfg.AddProfile<MappingProfile>();
            });

            IMapper mapper = config.CreateMapper();

            return mapper;
        });

        public static IMapper Mapper => Lazy.Value;
    }

几乎是逐字逐句的方法。

我有我的MappingProfile.csclass:

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<dynamic, FirstDTO>();
            CreateMap<dynamic, SecondDTO>();
        }
    }

当我调用我的基地class时,我有以下方法:

public class BaseLibraryClass : IBaseLibraryClass
    {
        public FirstDTO GetFirstObject(dynamic objectSentIn)
        {
            return Configuration.Mapper.Map<FirstDTO>(objectSentIn);
        }
    }

在我看来,应该可以。

现在,当我编写 xUnit 单元测试时,在将 FirstDTO 与内置 DTO 进行比较时,我遇到了失败 Assert.Equal:

        private readonly IBaseLibraryClass baseLibraryClass = new BaseLibraryClass();
        private readonly FirstDTOBuilder firstDTOBuilder = new FirstDTOBuilder();

        [Fact]
        public void TestSeparateObject()
        {
            // Arrange
            FirstDTO firstDTO = firstDTOBuilder.DefaultDTO().Build();

            // Act
            FirstDTO result = baseLibraryClass.GetFirstObject(firstDTO);

            // Assert
            Assert.Equal(firstDTO, result);
        }

当我调试这个单元测试时最终发生的事情是,一个 DTO 是通过 Builder 使用分配的属性构建的。它使用填充的属性成功地将 DTO 传递给 GetFirstObject,但是当它遇到 return 时,它 return 是一个 FirstDTO 对象类型,其属性全部归零,最终我的单元测试失败。

我觉得这是显而易见的事情,但我终究无法弄清楚是什么导致属性无法正确映射。

如有任何帮助,我们将不胜感激!

Automapper 支持开箱即用的 dynamic 映射,无需配置任何内容,因此在您的情况下,从配置中删除配置文件(或从配置文件中删除 CreateMap)应该只是工作:

public static class Configuration
{
    private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
        });

        IMapper mapper = config.CreateMapper();

        return mapper;
    });

    public static IMapper Mapper => Lazy.Value;
}