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.

Latest comments (0)

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.