DEV Community

Vinícius (Nico) Guedes
Vinícius (Nico) Guedes

Posted on

How to avoid AutoMapper configuration runtime errors

When working with AutoMapper, we often bump into runtime errors due to invalid mapping configuration, such as this one:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Wouldn't it be great if we could catch those errors before running our application?

AutoMapper actually provides an assertion that we can add to our Unit Tests pipeline and make sure that no runtime error will happen.

If you don't know how to create a Unit Test Project, follow the steps from this article: Getting Started with xUnit.net.

Using xUnit

public class MappingTests
{
    private readonly IConfigurationProvider _configuration;
    private readonly IMapper _mapper;

    public MappingTests()
    {
        _configuration = new MapperConfiguration(config => 
            config.AddProfile<MappingProfile>());

        _mapper = _configuration.CreateMapper();
    }

    [Fact]
    public void ShouldHaveValidConfiguration()
    {
        _configuration.AssertConfigurationIsValid();
    }
}
Enter fullscreen mode Exit fullscreen mode

Using NUnit

public class MappingTests
{
    private readonly IConfigurationProvider _configuration;
    private readonly IMapper _mapper;

    public MappingTests()
    {
        _configuration = new MapperConfiguration(config => 
            config.AddProfile<MappingProfile>());

        _mapper = _configuration.CreateMapper();
    }

    [Test]
    public void ShouldHaveValidConfiguration()
    {
        _configuration.AssertConfigurationIsValid();
    }
}
Enter fullscreen mode Exit fullscreen mode

The NUnit example was taken from the Clean Architecture Template, provided by Jason Taylor.

Please also check out the official AutoMapper Configuration Validation documentation.

Top comments (0)