How can I unit test an AutoMapper Profile which makes use of IMappingAction?

I’m using AutoMapper and I need to inject a service in one of my Profile classes.
AutoMapper Profile classes are not designed to support dependency injection, in this case the documented pattern is to use IMappingAction (see here for more details on this).

These are the classes that I need to map by using AutoMapper:

public sealed class Student
{
  public int Id { get; set; }
  public string FirstName { get; set; } = string.Empty;
  public string LastName { get; set; } = string.Empty;
  public DateOnly BirthDate { get; set; }
}

public sealed class StudentDto
{
  public string FullName { get; set; } = string.Empty;
  public DateOnly BirthDate { get; set; }
  public string SerialNumber { get; set; } = string.Empty;
}

This is the Profile class where the mapping between Student and StudentDto is configured:

public sealed class StudentProfile : Profile
{
  public StudentProfile()
  {
    CreateMap<Student, StudentDto>()
      .ForMember(
        studentDto => studentDto.FullName,
        options => options.MapFrom(student => $"{student.FirstName} {student.LastName}")
      )
      .ForMember(
        studentDto => studentDto.SerialNumber,
        options => options.Ignore()
      )
      .AfterMap<SetSerialNumberAction>();
  }
}

The Profile class references the following mapping action:

public sealed class SetSerialNumberAction : IMappingAction<Student, StudentDto>
{
  private readonly ISerialNumberProvider _serialNumberProvider;

  public SetSerialNumberAction(ISerialNumberProvider serialNumberProvider)
  {
    _serialNumberProvider = serialNumberProvider ?? throw new ArgumentNullException(nameof(serialNumberProvider));
  }

  public void Process(Student source, StudentDto destination, ResolutionContext context)
  {
    ArgumentNullException.ThrowIfNull(destination);

    destination.SerialNumber = _serialNumberProvider.GetSerialNumber();
  }
}

Finally, this is the service being injected in class SetSerialNumberAction:

public interface ISerialNumberProvider
{
  string GetSerialNumber();
}

public sealed class RandomSerialNumberProvider : ISerialNumberProvider
{
  public string GetSerialNumber() => $"Serial-Number-{Random.Shared.Next()}";
}

Since I am using ASP.NET core, I’m relying on Microsoft DI to compose all of my classes:

public static class Program
{
  public static void Main(string[] args)
  {
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.

    builder.Services.AddControllers();

    builder.Services.AddAutoMapper(typeof(StudentProfile));

    builder.Services.AddSingleton<ISerialNumberProvider, RandomSerialNumberProvider>();

    var app = builder.Build();

    // Configure the HTTP request pipeline.

    app.UseAuthorization();


    app.MapControllers();

    app.Run();
  }
}

Given this setup, I’m able to inject the IMapper service in my controller classes and everything works fine. Here is an example:

[ApiController]
[Route("api/[controller]")]
public class StudentsController : ControllerBase
{
  private static readonly ImmutableArray<Student> s_students =
  [
    new Student { Id = 1, BirthDate = new DateOnly(1988, 2, 6), FirstName = "Bob", LastName = "Brown" },
    new Student { Id = 2, BirthDate = new DateOnly(1991, 8, 4), FirstName = "Alice", LastName = "Red" },
  ];

  private readonly IMapper _mapper;

  public StudentsController(IMapper mapper)
  {
    _mapper = mapper;
  }

  [HttpGet]
  public IEnumerable<StudentDto> Get()
  {
    return s_students
      .Select(_mapper.Map<StudentDto>)
      .ToArray();
  }
}

The problem

The code written above works fine, the only problem is when it comes to unit testing.
The root cause of the problem I’m going to describe is that I’m relying on Microsoft DI to instantiate the Profile class, the mapping action SetSerialNumberAction and its dependency ISerialNumberProvider.

This is the way I usually write tests for AutoMapper’s Profile classes (this sample uses XUnit as the testing framework):

public sealed class MappingUnitTests
{
  private readonly MapperConfiguration _configuration;
  private readonly IMapper _sut;

  public MappingUnitTests()
  {
    _configuration = new MapperConfiguration(config =>
    {
      config.AddProfile<StudentProfile>();
    });

    _sut = _configuration.CreateMapper();
  }

  [Fact]
  public void Mapper_Configuration_Is_Valid()
  {
    // ASSERT
    _configuration.AssertConfigurationIsValid();
  }

  [Fact]
  public void Property_BirthDate_Is_Assigned_Right_Value()
  {
    // ARRANGE
    var student = new Student
    {
      FirstName = "Mario",
      LastName = "Rossi",
      Id = 1,
      BirthDate = new DateOnly(1980, 1, 5)
    };

    // ACT
    var result = _sut.Map<StudentDto>(student);

    // ASSERT
    Assert.NotNull(result);
    Assert.Equal(student.BirthDate, result.BirthDate);
  }

  [Fact]
  public void Property_FullName_Is_Assigned_Right_Value()
  {
    // ARRANGE
    var student = new Student
    {
      FirstName = "Mario",
      LastName = "Rossi",
      Id = 1,
      BirthDate = new DateOnly(1980, 1, 5)
    };

    // ACT
    var result = _sut.Map<StudentDto>(student);

    // ASSERT
    Assert.NotNull(result);
    Assert.Equal("Mario Rossi", result.FullName);
  }
}

Here there are 2 different problems:

  1. both tests Property_BirthDate_Is_Assigned_Right_Value and Property_FullName_Is_Assigned_Right_Value fail with the error System.MissingMethodException : Cannot dynamically create an instance of type ‘AutomapperUnitTestingSample.Mapping.SetSerialNumberAction’. Reason: No parameterless constructor defined.
  2. I don’t know how to inject a mock instance of ISerialNumberProvider in my tests in order to verify that the property StudentDto.SerialNumber is mapped correctly by using the SetSerialNumberAction mapping action.

A possible solution

The problem describer above can be solved by using Microsoft DI in the unit test.

For example, the following test class works fine and solve both problems described above:

public sealed class MappingUnitTestsWithContainer : IDisposable
{
  private readonly IMapper _sut;
  private readonly ServiceProvider _serviceProvider;
  private readonly Mock<ISerialNumberProvider> _mockSerialNumberProvider;

  public MappingUnitTestsWithContainer()
  {
    // init mock
    _mockSerialNumberProvider = new Mock<ISerialNumberProvider>();

    // configure services
    var services = new ServiceCollection();
    services.AddAutoMapper(typeof(StudentProfile));
    services.AddSingleton<ISerialNumberProvider>(_mockSerialNumberProvider.Object);

    // build service provider
    _serviceProvider = services.BuildServiceProvider();

    // create sut
    _sut = _serviceProvider.GetRequiredService<IMapper>();
  }

  [Fact]
  public void Mapper_Configuration_Is_Valid()
  {
    // ASSERT
    _sut.ConfigurationProvider.AssertConfigurationIsValid();
  }

  [Fact]
  public void Property_BirthDate_Is_Assigned_Right_Value()
  {
    // ARRANGE
    var student = new Student
    {
      FirstName = "Mario",
      LastName = "Rossi",
      Id = 1,
      BirthDate = new DateOnly(1980, 1, 5)
    };

    // ACT
    var result = _sut.Map<StudentDto>(student);

    // ASSERT
    Assert.NotNull(result);
    Assert.Equal(student.BirthDate, result.BirthDate);
  }

  [Fact]
  public void Property_FullName_Is_Assigned_Right_Value()
  {
    // ARRANGE
    var student = new Student
    {
      FirstName = "Mario",
      LastName = "Rossi",
      Id = 1,
      BirthDate = new DateOnly(1980, 1, 5)
    };

    // ACT
    var result = _sut.Map<StudentDto>(student);

    // ASSERT
    Assert.NotNull(result);
    Assert.Equal("Mario Rossi", result.FullName);
  }

  [Fact]
  public void Property_SerialNumber_Is_Set_By_Using_SetSerialNumberAction()
  {
    // ARRANGE
    var student = new Student
    {
      FirstName = "Mario",
      LastName = "Rossi",
      Id = 1,
      BirthDate = new DateOnly(1980, 1, 5)
    };

    // setup mock
    _mockSerialNumberProvider
      .Setup(m => m.GetSerialNumber())
      .Returns("serial-number-123");

    // ACT
    var result = _sut.Map<StudentDto>(student);

    // ASSERT
    Assert.NotNull(result);
    Assert.Equal("serial-number-123", result.SerialNumber);
  }

  public void Dispose()
  {
    _serviceProvider.Dispose();
  }
}

Is there a different solution to this problem ? Is it possible to solve this problem by not using a DI container in the unit test class ?

As a reference, I have created a GitHub repository which contains working code to showcase this problem.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật