【发布时间】:2016-01-03 02:21:29
【问题描述】:
我是 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);
}
这是详细信息方法。在调试模式下,只要我越过调用的 GetById 方法,我就会看到获取的 Story 为空。
【问题讨论】:
标签: c# asp.net-mvc mocking