testmethod中的Moq Automapper服务在映射时返回null

时间:2012-11-21 12:20:01

标签: asp.net-mvc unit-testing moq automapper

我正在MVC 4&amp ;;建立一个网站使用Automapper从域对象映射到Viewmodel对象。我按照http://rical.blogspot.in/2012/06/mocking-automapper-in-unit-testing.html

的说明注入了Automapper

并且在调试时它在action方法中运行良好,但是在我注入automapper服务时单元测试action方法时,我发现service.map返回null。但是调试映射时很好。我无法找到原因,尝试超过4小时。我有一个名为Interview& amp;的域名类。它的相应视图模型为InterviewModel。我已将映射初始化为CreateMap();在automapper配置文件配置中,已从全局启动方法调用。以下是控制器&行动...

public class NewsAndViewsController : Controller
{
    private IInterviewRepository repository;
    private IMappingService mappingService;

    public NewsAndViewsController(IInterviewRepository productRepository, IMappingService autoMapperMappingService)
    {
        repository = productRepository;
        mappingService = autoMapperMappingService;
    }

    [HttpPost, ValidateAntiForgeryToken]
    [UserId]
    public ActionResult Edit(InterviewModel interView, string userId)
    {
        if (ModelState.IsValid)
        {
            var interView1 = mappingService.Map<InterviewModel, Interview>(interView);
            **// THE ABOVE LINE RETURNING NULL WHILE RUNNING THE BELOW TEST, BUT NOT DURING DEBUGGING**
            repository.SaveInterview(interView1);
            TempData["message"] = string.Format("{0} has been saved", interView.Interviewee);
            return RedirectToAction("Create");
        }
        return View(interView);
    }
}

[TestMethod]
public void AddInterview()
{
    // Arrange
    var interviewRepository = new Mock<IInterviewRepository>();
    var mappingService = new Mock<IMappingService>();
    var im = new InterviewModel { Interviewee="sanjay", Interviewer="sanjay", Content="abc" };
    mappingService.Setup(m => m.Map<Interview, InterviewModel>(It.IsAny<Interview>())).Returns(im);
    var controller = new NewsAndViewsController(interviewRepository.Object, mappingService.Object);

    // Act
    var result = controller.Edit(im, "2") as ViewResult;

    // Assert - check the method result type
    Assert.IsNotInstanceOfType(result, typeof(ViewResult));
}

1 个答案:

答案 0 :(得分:1)

在你的测试中,你已经在mappedService.Setup()调用中划过了你的Interview和InterviewModel类(另外,我认为你可以使用更好的命名约定,或者不使用var来保存你的对象)明确 - “im”,“面试”和“面试1”不容易理解模型和视图对象。

试试这个:

[TestMethod]
public void AddInterview()
{
    // Arrange
    var interviewRepository = new Mock<IInterviewRepository>();
    var mappingService = new Mock<IMappingService>();
    var interview = new Interview();
    var im = new InterviewModel { Interviewee="sanjay", Interviewer="sanjay", Content="abc" };
    mappingService.Setup(m => m.Map<InterviewModel, Interview>(im).Returns(interview);
    var controller = new NewsAndViewsController(interviewRepository.Object, mappingService.Object);

    // Act
    var result = controller.Edit(im, "2") as ViewResult;

    // Assert - check the method result type
    Assert.IsNotInstanceOfType(result, typeof(ViewResult));
}