我是Moq的新手,并试图让我的模型在ASP.NET MVC中返回一个值。文档here。代码:
mock = new Mock<IRepository<Story>>();
mock.Setup(x => x.GetById( It.Is<int>( i => i==10 ) ))
.Returns(It.Is<Story>((Story story) => story.Id == 10 && story.Hits == 0));
storiesController = new StoriesController(mock.Object);
ViewResult result = storiesController.Details(10) as ViewResult;
和Details
方法调用storyRepository.GetById(id)
并且此测试失败:Assert.IsNotNull(result);
因为GetById
方法返回null。
我做错了什么?
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Story story = storyRepository.GetById(id);
if (story == null)
{
return HttpNotFound();
}
story.Hits++; // TODO!
storyRepository.Update(story);
storyRepository.Save();
return View(story);
}
这是Details方法。在调试模式下,当我跳过调用的GetById方法时,我看到获取的Story为null。
答案 0 :(得分:2)
它是因为Returns
的结果不是断言改为:
mock.Setup(x => x.GetById(10) ))
.Returns(new Story {Id=10 });