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:
- both tests
Property_BirthDate_Is_Assigned_Right_Value
andProperty_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. - I don’t know how to inject a mock instance of
ISerialNumberProvider
in my tests in order to verify that the propertyStudentDto.SerialNumber
is mapped correctly by using theSetSerialNumberAction
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.