How to mock Automapper (IMapper) in the controller

I am trying to write unit test for my existing MVC Web Application. In this, I ran into some problem in automapper ( IMapper). When I use the map function, it returns a value null.

My controller code:

public class UserAdministrationController : BaseController
{
    private readonly iUserService _userService;
    private readonly IMapper _mapper;

    public NewsController(iUserService userService, IMapper mapper)
    {
        _userService = userService;
        _mapper = mapper;
    }

    public ActionResult Create(int CompanyID == 0)
    {            
        UserDetail data = _userService(CompanyID);
        var Modeldata = _mapper.Map<UserDetailViewModel, UserDetail>(data);
        return View(Modeldata);
    }
} 

Mock Mapping Code:

public class MappingDataTest : CommonTestData
{
    public Mock<IMapper> MappingData()
    {
        var mappingService = new Mock<IMapper>();
        UserDetailViewModel interview = getUserDetailViewModel(); // get value of UserDetailViewModel
        UserDetail im = getUserDetail(); // get value of UserDetails

        mappingService.Setup(m => m.Map<UserDetail, UserDetailViewModel>(im)).Returns(interview);
        mappingService.Setup(m => m.Map<UserDetailViewModel, UserDetail>(interview)).Returns(im);

        return mappingService;
    }
}

Changeable code:

[TestClass]
public class UserAdminControllerTest
{
    private MappingDataTest _common;

    [TestInitialize]
    public void TestCommonData()
    {
        _common = new MappingDataTest();
    }

    [TestMethod]
    public void UserCreate()
    {
        //Arrange                                               
        UserAdministrationController controller = new UserAdministrationController(_common.mockUserService().Object, _common.MappingData().Object);
        controller.ControllerContext = _common.GetUserIdentity(controller);

        // Act
        ViewResult newResult = controller.Create() as ViewResult;

        // Assert
        Assert.IsNotNull(newResult);
    }
}

Mapper does not work, always displaying the value nullin the controller. kindly help me. Thanks at Advance.

+6
source share
2 answers

You should try the following:

public class MappingDataTest : CommonTestData
{
    public Mock<IMapper> MappingData()
    {
        var mappingService = new Mock<IMapper>();

        UserDetail im = getUserDetail(); // get value of UserDetails

        mappingService.Setup(m => m.Map<UserDetail, UserDetailViewModel>(It.IsAny<UserDetail>())).Returns(interview); // mapping data
        mappingService.Setup(m => m.Map<UserDetailViewModel, UserDetail>(It.IsAny<UserDetailtViewModel>())).Returns(im); // mapping data

        return mappingService;
    }
}

, UserDetailViewModel = getUserDetailViewModel(); , null. Null UserDetailViewModel UserDetailtViewModel .

+1

AutoMapper. , JSON-. .

+4

Source: https://habr.com/ru/post/1017040/


All Articles