我正在编写一些单元测试,我有一个场景,如果条件为真,控制器操作应该返回 a HttpNotFoundResult
,否则它应该返回 aViewResult
并在其中有一个特定的模型。
作为测试之一(测试它应该返回 a 的场景ViewResult
),我执行该操作,然后尝试将结果转换为 a ViewResult
。但是,当使用var result = myController.MyAction() as ViewResult
(where result
is 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