Moq Returns方法返回null

时间:2016-01-02 18:17:05

标签: c# asp.net-mvc mocking

我是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。

1 个答案:

答案 0 :(得分:2)

它是因为Returns的结果不是断言改为:

mock.Setup(x => x.GetById(10) ))
    .Returns(new Story {Id=10 });