如何在控制器中模拟Automapper(IMapper)

时间:2017-05-06 05:57:39

标签: c# asp.net-mvc unit-testing mocking automapper

我正在尝试为现有的MVC Web Aplication编写单元测试。因为我在automapper中遇到了一些问题(IMapper)每当使用map函数时它返回null值。

我的控制器代码:

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);
    }
} 

模拟映射代码:

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;
    }
}

模拟代码:

[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无法始终在控制器中显示null值。请帮助我。在此先感谢。

2 个答案:

答案 0 :(得分:7)

我建议不要嘲笑AutoMapper。在一个控制器单元测试中没有多少价值,这类似于模拟JSON序列化器。只需使用真实的东西。

答案 1 :(得分:2)

您应该尝试以下方法:

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的确切实例interview = getUserDetailViewModel();设置此映射,这就是它返回null的原因。 Null将期望对UserDetailViewModel的任何引用,并且对于UserDetailtViewModel的任何引用,它将返回预期的映射实例。