DEV Community

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

Posted on

2 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay