Whats the best way to setup a mock expection for the Map function in AutoMapper.
I extract the IMapper interface so I can setup expects for that interface. My mapper has dependencies, so I have to pass those in to the mapper.
What happens when I create 2 instances of my mapper class, with 2 different dependency implementations? I asume that both mappers will use the same dependency instance, since the AutoMapper map is static. Or AutoMapper might even throw an exception because I try to setup 2 different maps with the same objects.?
Whats the best way to solve this?
public interface IMapper { TTarget Map<TSource, TTarget>(TSource source); void ValidateMappingConfiguration(); } public class MyMapper : IMapper { private readonly IMyService service; public MyMapper(IMyService service) { this.service = service Mapper.CreateMap<MyModelClass, MyDTO>() .ForMember(d => d.RelatedData, o => o.MapFrom(s => service.getData(s.id).RelatedData)) } public void ValidateMappingConfiguration() { Mapper.AssertConfigurationIsValid(); } public TTarget Map<TSource, TTarget>(TSource source) { return Mapper.Map<TSource, TTarget>(source); } }
Whats the best way to setup a mock expection for the Map function in AutoMapper[?]
Here's one way:
var mapperMock = new Mock<IMapper>(); mapperMock.Setup(m => m.Map<Foo, Bar>(It.IsAny<Foo>())).Returns(new Bar());
You don't need to mock AutoMapper, you can just inject the real one as explained here:
var myProfile = new MyProfile(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(myProfile)); IMapper mapper = new Mapper(configuration);
You can inject this mapper in your unit tests. The whole point of using tools like AutoMapper is for you not having to write a lot of mapping code. If you mock AutoMapper you'll end up having to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With