MVC ViewResult.VIewName 即使设置后仍为空

MVC ViewResult.VIewName null even after setting it

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

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

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

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

这是我的单元测试:

[Test]
public void Index_ReturnCorrectView()
{
    var controller = new HomeController();
    var result = controller.Index("COMD") as ViewResult;
    Assert.AreEqual("Index", result.ViewName); 
}

我从单元测试中得到的错误是预期的 "Index",但结果为空。 我做了很多搜索,大多数答案都说 ViewName 属性 应该在返回视图时声明它之后设置。我也试过了,但还是不行。

谢谢

documentation for Controller.View() 状态:

This method overload of the View class returns a ViewResult object that has an empty ViewName property. If you are writing unit tests for controller actions, take into account the empty ViewName property for unit tests that do not take a string view name.

At run time, if the ViewName property is empty, the current action name is used in place of the ViewName property.

所以当期望一个与当前操作同名的视图时,我们可以测试它是一个空字符串。

或者,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");
    }