我是Just Mock的新手,面对通过这种方法的问题,需要帮助才能理解这个问题。
我有以下代码要测试
public ActionResult Create(JournalViewModel journal)
{
if (ModelState.IsValid)
{
var newJournal = _mapper.Map<JournalViewModel, Journal>(journal);// Mapper Updates cause syntax change
newJournal.UserId = (int)_membershipService.GetUser().ProviderUserKey;
var opStatus = _journalService.AddJournal(newJournal);
if (!opStatus.Status)
throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
return RedirectToAction("Index");
}
else
return View(journal);
}
以及我为测试编写的代码
[TestMethod()]
public void Create_return_journal()
{
var userMock = Mock.Create<MembershipUser>();
Mock.Arrange(() => userMock.ProviderUserKey).Returns(1);
Mock.Arrange(() => membershipService.GetUser()).Returns(userMock);
var opStatusMock = Mock.Create<OperationStatus>();
opStatusMock.Status = true;
Mock.Arrange(() => journalService.AddJournal(Mock.Create<Journal>())).Returns(opStatusMock);
//Act
PublisherController controller = new PublisherController(journalService, membershipService, mapper);
ViewResult actionResult = (ViewResult)controller.Create(Mock.Create<JournalViewModel>());
var model = actionResult.Model as JournalViewModel;
//Assert
Assert.IsNotNull(model);
}
在这里我期待opstatus.Status是真的但每次都变得虚假,这导致它进入
if (!opStatus.Status)
throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
TIA
答案 0 :(得分:0)
完成。以防万一有人在寻找答案。
我忘记了Mock Mapper。
以下是我用来解决此问题的代码。
[TestMethod()]
public void Create_return_journal()
{
var journalNew = Mock.Create<JournalViewModel>();
var journal = Mock.Create<Journal>();
Mock.Arrange(() => mapper.Map<JournalViewModel, Journal>(journalNew)).Returns(journal);
var userMock = Mock.Create<MembershipUser>();
Mock.Arrange(() => userMock.ProviderUserKey).Returns(1);
Mock.Arrange(() => membershipService.GetUser()).Returns(userMock);
var opStatusMock = Mock.Create<OperationStatus>();
opStatusMock.Status = true;
Mock.Arrange(() => journalService.AddJournal(journal)).Returns(opStatusMock);
//Act
PublisherController controller = new PublisherController(journalService, membershipService, mapper);
RedirectToRouteResult actionResult = (RedirectToRouteResult)controller.Create(journalNew);
//Assert
Assert.IsNotNull(actionResult);
}