单元测试控制器,其中包含自动映射

时间:2017-06-06 09:58:07

标签: unit-testing asp.net-web-api automapper

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

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

我现在想要对控制器进行单元测试。我的automapper配置如下所示:

    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();
        }
    }

如何对包含此自动机映射的控制器进行单元测试?

1 个答案:

答案 0 :(得分:1)

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

public class MyController : ApiController 
{
    private readonly IMapper _mapper;

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

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

以下是在Autofac容器中注册AutoMapper的示例,该容器只注册已添加到容器中的任何配置文件。您无需远眺任何其他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();