How to isolate AutoMapper in Unit Tests?
kernel.Bind<IMappingEngine>().ToConstant(Mapper.Engine);
services.AddInstance<IMappingEngine>(Mapper.Engine);
var mockMapper = new Mock<IMappingEngine>();
mockMapper.Setup(mock => mock.Map<TargetType>(It.IsAny<SourceType>())).Returns(targetInstance);
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class UserDto
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class Sut
{
private readonly IMappingEngine _mapper;
public Sut(IMappingEngine mapper)
{
_mapper = mapper;
}
public User Run(UserDto dto)
{
return _mapper.Map<User>(dto);
}
}
public class SutTests
{
[Fact]
public void RunShouldReturnUserCorrectly()
{
// arrange
var stubUser = new User();
var stubUserDto = new UserDto();
var mockMapper = new Mock<IMappingEngine>();
mockMapper.Setup(mock => mock.Map<User>(It.Is<UserDto>(stubUserDto))).Returns(stubUser);
var target = new Sut(mockMapper.Object);
// act
var actual = target.Run(stubUserDto);
// assert
Assert.AreEquals(stubUser, actual);
}
}