【问题标题】:MVC ViewResult.VIewName null even after setting itMVC ViewResult.VIewName null 即使在设置之后
【发布时间】:2018-01-24 23:10:34
【问题描述】:

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

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

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); 
}

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

谢谢

【问题讨论】:

  • 无关:你可能真的想要if (!string.IsNullOrEmpty(reportcode))
  • result 本身不为空吗?
  • @Andrei 没有结果是有效的 ViewResult

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


【解决方案1】:

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

【讨论】:

  • Controller.View(String) 正是 OP 正在使用的
  • @Andrei OP 必须像 Controller.View("Index", "COMD") 一样使用
  • @PowerStar 您好,谢谢您的回复。我不太确定 Controller.View("Index", "COMD") 是什么意思。这是我应该在 index 方法中返回的吗?我看不出它与我当前的实现有什么不同,因为不需要返回“COMD”
  • @PowerStar 好吧,所以这通过了测试!但是,我仍然有点困惑。这实际上是从我的控制器调用 index 方法吗?在我看来,它只是创建了一个带有名称索引的新视图对象,如果是这样,它就违背了单元测试的目的
  • @7uner 我在我的测试控制器中获得了预期值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
相关资源
最近更新 更多