I'm writing some unit tests and I have a scenario where, if a condition is true, a controller action should return a HttpNotFoundResult
, otherwise it should return a ViewResult
and have a specific Model inside of it.
As one of the tests (testing the scenario where it should return a ViewResult
), I execute the action and then try and cast the result to a ViewResult
. However, when using var result = myController.MyAction() as ViewResult
(where result
is an ActionResult
), result
always evaluates to null... but when I do var result = (ViewResult)myController.MyAction()
, the result is casted just fine.
Why is this? Do I not understand the usage of as
properly?
Relevant code:
// 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?
}
EDIT: Full example with gist. Sorry, it seems that it doesnt' like the syntax highlighting. https://gist.github.com/DanPantry/dcd1d55651d220835899