将ActionResult强制转换为HttpNotFoundResult将返回null

时间:2014-03-13 13:53:55

标签: asp.net mstest asp.net-mvc-5 justmock

我对我的控制器进行了单元测试,断言在找不到模型的实例时会返回HttpNotFoundResult。问题是,控制器中的实际代码是按预期工作的,但我的单元测试不是。将ActionResult强制转换为HttpNotFoundResult时,它返回null,因此我的单元测试失败。

控制器代码:

public ActionResult Delete(int? id)
        {
            if(id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Forum forum = forumRepository.GetForumById(id.GetValueOrDefault());
            if(forum == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            return View(forum);
        }

测试方法:

 [TestMethod]
        public void GetDeleteShouldReturn404IfForumNotFound()
        {
            // Arrange
            var forumRepository = Mock.Create<IForumRepository>();
            Mock.Arrange(() => forumRepository.GetForums())
                .Returns(new List<Forum>() {
                    new Forum { ForumId = 1, Title = "General Forum", Description = "Place to discuss general stuff", Sequence = 2 },
                    new Forum { ForumId = 2, Title = "Gaming", Description = "Let's talk about gaming", Sequence = 1 },
                    new Forum { ForumId = 3, Title = "Web Development", Description = "ASP.NET is pretty cool", Sequence = 3 }
                }).MustBeCalled();

            // Act
            ForumController controller = new ForumController(forumRepository);
            ActionResult result = controller.Delete(5) as HttpNotFoundResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }

Assert.IsNotNull失败。我也尝试了以下相同的结果:

HttpNotFoundResult result = controller.Delete(5) as HttpNotFoundResult;

这令人难以置信,因为我在几个例子中看到了几乎相同的代码:

http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-using-httpnotfoundresult-in-controller-tests.aspx

我做错了吗?

编辑:

问题是我没有嘲笑GetForumById(),将测试代码更改为以下工作:

[TestMethod]
        public void GetDeleteShouldReturn404IfForumNotFound()
        {
            // Arrange
            var id = 10;
            Forum forum = null;

            var forumRepository = Mock.Create<IForumRepository>();

            Mock.Arrange(() => forumRepository.GetForumById(id))
                .Returns(forum)
                .MustBeCalled();

            // Act
            ForumController controller = new ForumController(forumRepository);
            var result = controller.Delete(id) as HttpNotFoundResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }

1 个答案:

答案 0 :(得分:2)

这是因为HttpNotFoundResult来自HttpStatusCodeResult,而不是相反。您正在进行无效的向下转换,使as语句返回null。