How to Mock an AutoMapper IMapper object in Web API Tests With StructureMap Dependency Injection?

Viewed 18584

So I've build a WebAPI from scratch, including some best practices that I've found online such as Dependency Injection and Domain<->DTO mapping using auto mapper etc.

My API Controllers now look similar to this

public MyController(IMapper mapper)
{
}

and AutoMapper Registry:

public AutoMapperRegistry()
{
    var profiles = from t in typeof(AutoMapperRegistry).Assembly.GetTypes()
                    where typeof(Profile).IsAssignableFrom(t)
                    select (Profile)Activator.CreateInstance(t);
    
    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });

    For<MapperConfiguration>().Use(config);
    For<IMapper>().Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));
}

I'm also building a few test cases, implementing MOQ, and this is where i feel a little unsure. whenever calling my controllers, I need to pass in an IMapper like this:

var mockMapper = new Mock<IMapper>();
var controller = new MyController(mockMapper.Object);

But then, how do i configure the IMapper to have the correct mappings? It feels redundant to recreate the same logic I've already created before to configure the Mapper. so I am wondering what is the recommended approach to do this?

2 Answers

This might me another solution

//auto mapper configuration
var mockMapper = new MapperConfiguration(cfg =>
{
    cfg.AddProfile(new AutoMapperProfile()); //your automapperprofile 
});
var mapper = mockMapper.CreateMapper();

And then call then controller like so

var controller = new YourController(imapper:mapper,..otherobjects..);

This way it will serve the purpose or else if you create mock object for IMapper then it will return what you ask it to return.

Related