测试Automapper配置文件的单元测试

53

我确实想测试CreateMap方法中的自定义逻辑。但我不想测试某些类型的映射是否存在。

我应该如何做,或者需要了解哪些类?感谢任何提示。有关Automapper单元测试的文档似乎非常罕见...

public class UnitProfile : Profile
{
   protected override void Configure()
   {
      // Here I create my maps with custom logic that needs to be tested

    CreateMap<Unit, UnitTreeViewModel>()
         .ForMember(dest => dest.IsFolder, o => o.MapFrom(src => src.UnitTypeState == UnitType.Folder ? true : false));

    CreateMap<CreateUnitViewModel, Unit>()
         .ForMember(dest => dest.UnitTypeState, o => o.MapFrom(src => (UnitType)Enum.ToObject(typeof(UnitType), src.SelectedFolderTypeId)));
   }
}
2个回答

41

1
我感觉少了点什么。为什么你不能编写一个单元测试,创建一个 Unit 实例,将其映射到 UnitTreeViewModel,并断言映射后的对象是否符合预期? - Mightymuke
5
这是个好问题。我猜那是因为在我的这边快到半夜了;-) - Pascal
1
好的,我明白了:Mapper.AddProfile(new UnitProfile()); 现在一切都正常 :) - Pascal

28

Automapper配置文件的测试示例(我使用的是Automapper版本10.0.0和NUnit版本3.12.0):

RowStatusEnum

namespace StackOverflow.RowStatus
{
    public enum RowStatusEnum
    {
        Modified = 1,
        Removed = 2,
        Added = 3
    }
}

我的个人资料

namespace StackOverflow.RowStatus
{
    using System;
    using System.Linq;

    using AutoMapper;

    public class MyProfile : Profile
    {
        public MyProfile()
        {
            CreateMap<byte, RowStatusEnum>().ConvertUsing(
                x => Enum.GetValues(typeof(RowStatusEnum))
                    .Cast<RowStatusEnum>().First(y => (byte)y == x));
            CreateMap<RowStatusEnum, byte>().ConvertUsing(
                x => (byte)x);
        }
    }
}

映射测试

namespace StackOverflow.RowStatus
{
    using AutoMapper;

    using NUnit.Framework;

    [TestFixture]
    public class MappingTests
    {
        [Test]
        public void AutoMapper_Configuration_IsValid()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile<MyProfile>());
            config.AssertConfigurationIsValid();
        }

        [TestCase(1, ExpectedResult = RowStatusEnum.Modified)]
        [TestCase(2, ExpectedResult = RowStatusEnum.Removed)]
        [TestCase(3, ExpectedResult = RowStatusEnum.Added)]
        public RowStatusEnum AutoMapper_ConvertFromByte_IsValid(
            byte rowStatusEnum)
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile<MyProfile>());
            var mapper = config.CreateMapper();
            return mapper.Map<byte, RowStatusEnum>(rowStatusEnum);
        }

        [TestCase(RowStatusEnum.Modified, ExpectedResult = 1)]
        [TestCase(RowStatusEnum.Removed, ExpectedResult = 2)]
        [TestCase(RowStatusEnum.Added, ExpectedResult = 3)]
        public byte AutoMapper_ConvertFromEnum_IsValid(
            RowStatusEnum rowStatusEnum)
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile<MyProfile>());
            var mapper = config.CreateMapper();
            return mapper.Map<RowStatusEnum, byte>(rowStatusEnum);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接