Reputation: 147
I have an asp.net webapi project, in which I have a controller that I want to unit test. In that controller I have a mapping. The controller inherits from a base controller, of which the implementation is:
public class BaseController : ApiController
{
/// <summary>
/// AutoMapper Mapper instance to handle all mapping.
/// </summary>
protected IMapper GlobalMapper => AutoMapperConfig.Mapper;
}
I now want to unit test the controller. My automapper configuration looks like this:
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();
}
}
How can I unit test the controller that has this automapper mapping in it?
Upvotes: 1
Views: 857
Reputation: 30628
My recommendation would be to use Dependency Injection. Each controller would take a dependency on an IMapper instance, which would be provided by your DI container. This makes unit testing much easier.
public class MyController : ApiController
{
private readonly IMapper _mapper;
public MyController(IMapper mapper)
{
_mapper = mapper;
}
}
Don't use the static AutoMapper instance (e.g. Mapper.Map(...)
) at all.
Here's a sample for getting AutoMapper registered in an Autofac container, which just registers any profiles which have been added to the container. You won't have to look far to find equivalent samples for any other DI container.
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();
Upvotes: 1