2017-06-06 104 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