gpt4 book ai didi

asp.net-mvc - 测试方法中的 Moq Automapper 服务在映射时返回 null

转载 作者:行者123 更新时间:2023-12-03 21:08:56 24 4
gpt4 key购买 nike

我正在使用 MVC 4 构建网站并使用 Automapper 从域对象映射到 Viewmodel 对象。我已经按照此处所述注入(inject)了 Automapper http://rical.blogspot.in/2012/06/mocking-automapper-in-unit-testing.html

它在调试时在操作方法内部工作正常,但在单元测试操作方法期间,当我注入(inject)自动映射器服务时,我发现 service.map 返回 null。但是在调试映射时很好。我无法找到原因,尝试超过 4 小时。我有一个名为 Interview 的域类,其对应的 View 模型为 InterviewModel。我已将映射初始化为 CreateMap();在 automapper 配置文件配置中,已从全局启动方法调用。下面是 Controller 和 Action ...

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

最佳答案

在您的测试中,您的 Interview 和 InterviewModel 类在 mappingService.Setup() 调用中交叉(顺便说一句,我认为您可以使用更好的命名约定,或者不使用 var,以保留您的对象清晰 - “im”、“interview” 和 “interview1” 让人很难理解哪个是模型,哪个是 View 对象)。

试试这个:

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

关于asp.net-mvc - 测试方法中的 Moq Automapper 服务在映射时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13493112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com