【问题标题】:Moq Returns method returns nullMoq Returns 方法返回 null
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 我会尽快做,它说我可以在 5 分钟内标记
    • @Johnath 好的,别忘了。
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 2018-04-05
    相关资源
    最近更新 更多