Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock AutoMapper Mapper.Map call using Moq

Tags:

c#

moq

automapper

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);     } } 
like image 347
Alex Johansson Avatar asked Feb 26 '10 09:02

Alex Johansson


2 Answers

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()); 
like image 106
Mark Seemann Avatar answered Sep 28 '22 09:09

Mark Seemann


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.

like image 28
ataravati Avatar answered Sep 28 '22 07:09

ataravati