2015-05-28 55 views
4

我希望能夠遍歷映射爲源(或目標)的每種類型的程序集,並驗證映射配置是否有效。這是一個相當大的項目,廣泛使用AutoMapper,當開發人員引入無效的映射關係時,我希望這個單元測試能夠中斷。查看GetAllMappedTypes,GetPropertyMaps的集合,但我似乎無法獲得檢查有效配置的方法。我們使用AutoMapper的v4。查找並驗證所有自動映射器映射

回答

3

這樣做的automapper代碼:

<Perform mapping configuration work> 

Mapper.AssertConfigurationIsValid() 

如果你使用NUnit,你可以這樣做:

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

的mappingconfig是我多麼初始化我的映射。我在MVC中使用automapper,因此我所有的靜態配置都發生在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(); 
    } 
} 
+0

對不起,但我在你提供的nUnit例子中缺少一些東西。我沒有看到任何類型的MappingConfig。你能幫我填補空白嗎?應該提到,我在這裏學習AutoMapper。 – Ron

+0

我簡化了代碼併發布了我正在使用的mappingconfig。 –