Ron
Ron

Reputation: 907

Find and validate all automapper mappings

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.

Upvotes: 6

Views: 1796

Answers (1)

C Bauer
C Bauer

Reputation: 5103

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();
    }
}

Upvotes: 4

Related Questions