3

我正在编写一些单元测试,我有一个场景,如果条件为真,控制器操作应该返回 a HttpNotFoundResult,否则它应该返回 aViewResult并在其中有一个特定的模型。

作为测试之一(测试它应该返回 a 的场景ViewResult),我执行该操作,然后尝试将结果转换为 a ViewResult。但是,当使用var result = myController.MyAction() as ViewResult(where resultis an ActionResult) 时,result总是评估为 null...但是当我这样做时var result = (ViewResult)myController.MyAction(),结果会很好地转换。

为什么是这样?我不理解as正确的用法吗?

相关代码:

// My controller
public class MyController
{
  .. 
  public ActionResult MyAction(bool condition)
  {
      if(condition)
         return HttpNotFound()
      return View(new object());
  }
}

// My test
public void MyTest()
{
  ....
  var controller = new MyController();
  var result = controller.MyAction(false) as ViewResult;
  // result should be casted successfully by as, but it's not, instead it's unll
  // however, this works
  var result = (ViewResult) controller.MyAction(false);
  // why is this?
}

编辑:带有要点的完整示例。抱歉,它似乎不喜欢语法突出显示。 https://gist.github.com/DanPantry/dcd1d55651d220835899

4

1 回答 1

2

由于没有人回答 - 我将我的 ASP MVC 更新为 ASP MVC 5,然后测试成功了。我有一种直觉,我的测试项目使用的是 ASP MVC 5,但包含控制器的项目正在运行 ASP MVC 4,并且因为它们来自不同的二进制文件,控制器类可能会ViewResult在 的阴影中返回 a ActionResult,但测试项目无法从ViewResultto转换,ActionResult因为它的理解ViewResult不同。

虽然这看起来很愚蠢,因为有人会认为在这种情况下我会遇到构建错误。

哦,好吧,升级修复了它。

于 2014-02-11T11:09:35.703 回答