MVC ViewResult.VIewName即使在设置之后也为null

时间:2017-08-16 17:34:59

标签: asp.net-mvc unit-testing viewresult

我正在尝试为MVC应用程序编写单元测试。我试图测试我的控制器是否返回正确的视图名称。

这是我正在测试的控制器动作:

<key>Program</key>

这是我的Unittest:

public IActionResult Index(string reportcode)
{
    if(string.IsNullOrEmpty(reportcode))
          ReportCode = reportcode;

     ViewBag.GridSource = GetReportData(reportcode);
     return View("Index");
}

我预计会从单元测试中得到错误&#34;索引&#34;但是没有了。 我做了很多搜索,大多数答案都说在返回视图后声明ViewName属性。我尝试了同样但它不会工作。

谢谢

1 个答案:

答案 0 :(得分:2)

documentation for Controller.View()州:

  

View类的此方法重载返回一个ViewResult对象   具有空ViewName属性。如果你正在编写单元测试   控制器动作,考虑到空的ViewName属性   不采用字符串视图名称的单元测试。

     

在运行时,如果ViewName属性为空,则为当前操作   name用于代替ViewName属性。

因此,当期望与当前操作同名的视图时,我们可以测试它是否为空字符串。

或者,Controller.View(ViewName,Model)方法将设置ViewName。

我的控制器方法

    public ActionResult Index()
    {
      return View("Index");
    }

测试方法

    [TestMethod]
    public void Index()
    {
        // Arrange
        HomeController controller = new HomeController();

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

        // Assert
        Assert.IsTrue(result.ViewName == "Index");
    }
相关问题