2013-04-22 110 views
7

我在使用一個大的AutoMapperConfiguration類來使用實際配置文件來滾動我的AutoMapper。全球現在看起來像這樣(原諒打開/關閉違反現在)AutoMapper配置文件和單元測試

Mapper.Initialize(x => 
         { 
          x.AddProfile<ABCMappingProfile>(); 
          x.AddProfile<XYZMappingProfile>(); 
          // etc., etc. 
        }); 

這讓我在上面的關鍵部分,並在前面設置的障礙總是阻止了我使用的配置文件是我ninject結合。我永遠無法使綁定工作。 之前我有這個結合:

Bind<IMappingEngine>().ToConstant(Mapper.Engine).InSingletonScope(); 

因爲我已經遷移到該綁定:

Bind<IMappingEngine>().ToMethod(context => Mapper.Engine); 

現在這工作,該應用程序是功能性的,我有譜了,東西都不錯。

順利現在在我的單元測試。使用NUnit,我會設置我的構造函數依賴。

private readonly IMappingEngine _mappingEngine = Mapper.Engine; 

然後在我的[Setup]方法中,我將構建我的MVC控制器並調用AutoMapperConfiguration類。

[SetUp] 
public void Setup() 
{ 
    _apiController = new ApiController(_mappingEngine); 
    AutoMapperConfiguration.Configure(); 
} 

我現在已經修改了。

[SetUp] 
public void Setup() 
{ 
    _apiController = new ApiController(_mappingEngine); 

    Mapper.Initialize(x => 
          { 
           x.AddProfile<ABCMappingProfile>(); 
           x.AddProfile<XYZMappingProfile>(); 
           // etc., etc. 
          }); 
} 

不幸的是,這似乎並不奏效。當我點擊一個使用映射的方法時,映射似乎沒有被拾取,AutoMapper拋出一個異常,指出映射不存在。有關如何/在測試中更改映射器定義/注入以解決此問題的任何建議?我猜IMappingEngine字段的定義是我的問題,但不確定我有什麼選項。

感謝

回答

3

問題,你必須是使用靜態Mapper.Engine這是某種形式的單身人士,其中包含AutoMapper配置的結果。按照慣例,Mapper.Engine配置後不應更改。因此,如果您想爲每個unittest提供AutoMapper.Profiler來配置Automapper,則應避免使用它。

的變化是相當簡單:添加到您的實例類AutoMapperConfiguration它自己的實例AutoMapper.MappingEngine,而不是使用全局靜態Mapper.Engine

public class AutoMapperConfiguration 
{ 
    private volatile bool _isMappinginitialized; 
    // now AutoMapperConfiguration contains its own engine instance 
    private MappingEngine _mappingEngine; 

    private void Configure() 
    { 
     var configStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers()); 

     configStore.AddProfile(new ABCMappingProfile()); 
     configStore.AddProfile(new XYZMappingProfile()); 

     _mappingEngine = new MappingEngine(configStore); 

     _isMappinginitialized = true; 
    } 

    /* other methods */ 
} 

PS:full sample is here

+0

對不起,我還沒有得到回覆你呢。我運行了一個測試,並且你的Git確實能夠運行,但是當我試圖將引擎作爲構造參數拉出時,事情就會消失。今晚我會圍繞着進一步測試。 – Khepri 2013-04-24 20:45:58

+0

今天早上我已經驗證過,作爲一個獨立的解決方案,你的git可以滿足你的期望。但是,對於我試圖將IMappingEngine的實例作爲使用Ninject的構造函數參數傳遞的場景,我仍然沒有收到初始化的映射。我使用了git,並添加了一個方法來返回已初始化的MappingEngine,並嘗試將其作爲構造函數參數傳遞。結果是一樣的。 – Khepri 2013-04-28 15:53:34

+0

您是否嘗試用'MappingEngine'的新獨立實例將_all_ calls/refences替換爲'Mapper'('Mapper.Initialize','Mapper.Engine'等)? – Akim 2013-04-28 20:13:44