DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›