我正在尝试使用XUnit进行单元测试,以获得ASP.NET v5 MVC v6应用程序。我可以对工作方法进行简单的单元测试。我想测试控制器。现在,我有一个带有Index动作的HomeController,它返回Home / Index视图。我想测试Index视图是返回的视图。
这是我目前的测试文件:
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);
}
}
}
这里的Controllers / 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中找到Index视图?
答案 0 :(得分:3)
听起来你正在尝试测试框架中的功能,而不是测试方法中的功能。方法中的所有内容都是:
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应用程序并测试该应用程序以测试该功能,这更像是一个黑盒测试,而不是单元测试。
答案 1 :(得分: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");
}
}
}