2017-06-06 103 views
0

我有一个asp.net webapi项目,其中我有一个控制器,我想单元测试。在那个控制器中我有一个映射。控制器继承自一个基本控制器,其实施是:单元测试一个控制器与自动映射器映射它

public class BaseController : ApiController 
{ 
    /// <summary> 
    /// AutoMapper Mapper instance to handle all mapping. 
    /// </summary> 
    protected IMapper GlobalMapper => AutoMapperConfig.Mapper; 
} 

我现在想单元测试控制器。我的自动映射器配置如下所示:

public static class AutoMapperConfig 
    { 
     /// <summary> 
     /// Provides access to the AutoMapper configuration. 
     /// </summary> 
     public static MapperConfiguration MapperConfiguration { get; private set; } 

     /// <summary> 
     /// Provides access to the instance of the AutoMapper Mapper object to perform mappings. 
     /// </summary> 
     public static IMapper Mapper { get; private set; } 

     /// <summary> 
     /// Starts the configuration of the mapping. 
     /// </summary> 
     public static void Start() 
     { 
      MapperConfiguration = new MapperConfiguration(cfg => 
      { 
       cfg.AddProfile<MeldingProfiel>(); 
       cfg.AddProfile<GebouwProfiel>(); 
       cfg.AddProfile<AdresProfiel>(); 
      }); 

      MapperConfiguration.AssertConfigurationIsValid(); 

      Mapper = MapperConfiguration.CreateMapper(); 
     } 
    } 

我该如何测试具有此自动映射器映射的控制器?

+0

究竟你想测试什么? –

+0

如果我的控制器返回我希望它返回的事物的列表。 – AyatollahOfRockNRolla

回答

1

我的建议是使用依赖注入。每个控制器都会依赖一个IMapper实例,该实例将由您的DI容器提供。这使得单元测试更容易。

public class MyController : ApiController 
{ 
    private readonly IMapper _mapper; 

    public MyController(IMapper mapper) 
    { 
     _mapper = mapper; 
    } 
} 

都不要使用静态AutoMapper实例(例如Mapper.Map(...))。

下面是一个获取AutoMapper注册到Autofac容器的示例,该容器只注册已添加到容器中的任何配置文件。您不必远近寻找任何其他DI容器的同等样本。

builder.Register<IMapper>(c => 
{ 
    var profiles = c.Resolve<IEnumerable<Profile>>(); 
    var config = new MapperConfiguration(cfg => 
    { 
     foreach (var profile in profiles) 
     { 
      cfg.AddProfile(profile); 
     } 
    }); 
    return config.CreateMapper(); 
}).SingleInstance(); 
+0

太棒了,谢谢! – AyatollahOfRockNRolla