我有一个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();
}
}
如何单元测试其中包含此汽车映射的控制器?
我的建议是使用依赖注入。每个控制器将依赖于IMApper实例,该实例将由您的DI容器提供。这使单元测试变得更加容易。
public class MyController : ApiController
{
private readonly IMapper _mapper;
public MyController(IMapper mapper)
{
_mapper = mapper;
}
}
完全不要使用静态自动应用程序实例(例如Mapper.Map(...)
(。
这是用于在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();