Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and validate all automapper mappings

Tags:

c#

automapper

I would like to be able to traverse an assembly for each type that is mapped as a source (or destination), and verify that the mapping configuration is valid. This is for a rather large project that uses AutoMapper extensively and I'd like this unit test to break when a dev introduces an invalid mapping relationship. Looking at collection of GetAllMappedTypes, GetPropertyMaps, but I don't seem to be able to get to a way to check for a valid configuration. We're using v4 of AutoMapper.

like image 765
Ron Avatar asked Oct 19 '22 10:10

Ron


1 Answers

The automapper code for this is:

<Perform mapping configuration work>

Mapper.AssertConfigurationIsValid()

If you're using nunit, you can do:

    [TestFixture]
    public class when_validating_mapping_config
    {
        [Test]
        public void then_should_assert_mapping_configuration_is_valid()
        {
            // Arrange
            MappingConfig.InitializeMappings(); // this is just however you initialize your mappings.

            // Act

            // Assert
            Mapper.AssertConfigurationIsValid();
        }
    }

The mappingconfig is just how I initialize my mappings. I am using automapper in MVC so all my static configuration happens in Global.asax.cs.

public static class MappingConfig
{
    public static void InitializeMappings()
    {
        Mapper.Initialize(configuration => Configure(configuration));
    }

    public static void Configure(IConfiguration configuration)
    {

        configuration.CreateMap<Model, ViewModel>()
        configuration.Seal();
    }
}
like image 74
C Bauer Avatar answered Oct 21 '22 23:10

C Bauer