2016-01-13 186 views
3

我正在嘗試將XUnit的單元測試用於ASP.NET v5 MVC v6應用程序。我可以在工作方法上進行簡單的單元測試。我想測試控制器。現在,我有一個帶有索引操作的HomeController,它返回Home/Index視圖。我想測試索引視圖是返回的。ASP.NET MVC:使用XUnit測試控制器

這是我目前的測試文件:

using Microsoft.AspNet.Mvc; 
using Xunit; 
using XUnitWithMvcSample.Controllers; 

namespace XUnitWithMvcSample.Tests 
{ 
    public class Tests 
    { 
     private HomeController _homeController; 
     public Tests() 
     { 
      _homeController = new HomeController(); 
     } 
     [Fact] 
     public void IndexActionReturnsIndexView() 
     { 
      var result = _homeController.Index() as ViewResult; 
      System.Console.WriteLine(result); 
      Assert.Equal("Index", result.ViewName); 
     } 

    } 
} 

這裏的控制器/ HomeController.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNet.Mvc; 


namespace XUnitWithMvcSample.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public IActionResult Index() 
     { 
      return View(); 
     } 
    } 
} 

當我運行測試,它失敗了,因爲result.ViewName爲空。它看起來像result只是一個空的ViewResult_homeController無關。我需要做什麼才能使測試在HomeController中找到索引視圖?

回答

2

這聽起來像你試圖測試框架中的功能,而不是方法中的功能。所有這一切是在方法是這樣的:

return View(); 

所以,從字面上看,只要返回一個非空ViewResult,則該方法做什麼它應該做的:

// Arrange 
var controller = new HomeController(); 

// Act 
var result = controller.Index() as ViewResult; 

// Assert 
Assert.IsNotNull(result); 

鏈接該結果到一個視圖是ASP.NET MVC框架的一部分,併發生在該方法之外。這意味着它不是方法調用本身的一部分,但發生在方法範圍之外。這超出了測試範圍。

您必須設置一種正在運行的ASP.NET MVC應用程序並測試該應用程序才能測試該功能,這比單元測試更像是黑盒測試。

0

這有點晚,但如果你可以改變你的動作方法,你的測試將會奏效。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNet.Mvc; 


namespace XUnitWithMvcSample.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public IActionResult Index() 
     { 
      return View("Index"); 
     } 
    } 
}