Search code examples
c#unit-testingasp.net-coredependency-injectionautomapper

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 solves 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.


Solution

  • Is there a different solution to this problem?

    Yes. Simply do not use DI within AutoMapper.

    But... I want to use DI within AutoMapper.

    Then sorry, but you are using AutoMapper wrong. Maybe you are not seeing it now, but you will see it in the future if you continue to use AutoMapper throughout forthcoming projects.

    As Jimmy Bogard, the author of AutoMapper, said in his post about AutoMapper's Design Philosophy:

    AutoMapper works because it enforces a convention. It assumes that your destination types are a subset of the source type. It assumes that everything on your destination type is meant to be mapped. It assumes that the destination member names follow the exact name of the source type. It assumes that you want to flatten complex models into simple ones.

    To me, it also assumes that what you are trying to map is simple, yet omnipresent so you don't want to do the process manually, because there is too much of boring code to write. Key to getting the best from AutoMapper and not getting the nasty side effects is keeping things simple. Knowing when to use it, when not and recognizing the moment where you should opt for unit-testable, custom-made, manual approach rather than AutoMapper.

    I'm aware that AutoMapper supports DI within itself, but in my opinion, the moment when you need DI in order to map some models, it stops being simple, I'm afraid. Remember that it is supposed to be simple and leave your project in a better state that before using that library. Keeping things simple keeps your codebase maintainability level at bay.

    On the other hand, letting custom resolvers, DI, after or before map wildly grow around your profiles will come back at you or programmers coming after you trying to extend or fix the code you left. Letting your business logic (and yes, setting a serial number is business logic) into your mapping profiles is a mistake, and it will affect the maintainability of your code. You've experienced that already, because you've noticed how testing such mapping configuration is difficult. Now imagine trying to find some bug in a project that has half of its business logic scattered around mapping profiles. I've seen cases like that and trust me, it is quite a nightmare. StackOverflow itself is full of questions with code like that.

    Also, take a look at Jimmy's AutoMapper Usage Guidelines. Worth a read.

    Testing

    AutoMapper has a unique feature that distinguish it from other mapping libraries, and that is configuration validation. It works best if you have an integration test set up that creates a mapper from all your profiles, then checks whether its configuration is valid. With simple mapping profiles, it is all that you need. AutoMapper will automatically detect when e.g. somebody added a new property and now mapping for it is missing. Paired with CI, this will give you a great level of control over your models.

    public class AutoMapperTests : IClassFixture<WebApplicationFactory<Program>>
    {
        private readonly WebApplicationFactory<Program> _factory;
    
        public AutoMapperTests(WebApplicationFactory<Program> factory)
        {
            _factory = factory;
        }
    
        [Fact]
        public void Should_Not_Throw_WithValidConfiguration()
        {
            // Assert
            // Get mapper from service provider.
            // DO NOT create it manually if your mapping profiles use DI.
        
            // Act
            var exception = Record.Exception(() => mapper.ConfigurationProvider.AssertConfigurationIsValid());
    
            // Assert
            Assert.Null(exception);
        }
    }
    

    What to do?

    So, that was quite a rant... but what actual steps you should take in your scenario?

    1. If you really need to set that serial number right after mapping and consider it a single process, that you can wrap that logic in your own mapper. Nothing stops you from having a dependency on AutoMapper in your dedicated mapping approach, so you can leave out the simple stuff for AutoMapper and do the business logic in a dedicated mapper.

    2. Or... simply do the business logic after the mapping, after you called AutoMapper. That obviously has a downside that you need to remember to always do it in every place and there is a risk you are going to forget about it. So, consider point 1. ☝️