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

That's pretty simple: if you mock IMapper and imagine it as a fully abstract concept of mapping data from one object to another, then you have to treat is an abstraction and not imply there's a real automapper behind it.

First you should not register any existing profile at all, you should instead setup IMapper.Map method to return specific object when given another object.

So for each profile used for specific method you have to do a setup, looking approximately like this:

var mockMapper = new Mock<IMapper>();
mockMapper.Setup(x => x.Map<DestinationClass>(It.IsAny<SourceClass>()))
    .Returns((SourceClass source) =>
        {
            // abstract mapping function code here, return instance of DestinationClass
        });

In this case, your test knows nothing about actual IMapper implementation - it just uses it methods to get the data you expect from actual IMapper implementation to receive.


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.