2014-03-13 70 views
3

我有一個單元測試我的控制器,斷言當找不到模型的實例時返回HttpNotFoundResult。問題是,控制器中的實際代碼按預期工作,但我的單元測試不是。將ActionResult轉換爲HttpNotFoundResult時,它返回null,因此我的單元測試失敗。Casting ActionResult as 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)); 
     } 

回答

2

這是因爲HttpNotFoundResultHttpStatusCodeResult派生,而不是周圍的其他方法。你正在使一個無效的downcast,這使得as語句返回null。

+0

你會建議我將代碼更改爲?我曾嘗試在控制器(它返回HttpNotFoundResult類的一個實例)中使用'return HttpNotFound()',但這也不起作用。 – Soldat1988

+0

@ Soldat1988'controller.Delete(5)'返回什麼?它的類型是什麼? –

+0

在這種情況下,如果我在控制器操作中使用'return HttpNotFound()',它應該返回一個類型爲'HttpNotFoundResult'的值。 – Soldat1988