2013-04-22 107 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