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
As no one has answered - I updated my ASP MVC to ASP MVC 5 and the tests then succeeded. I have a gut feeling that my test project was using ASP MVC 5, but the project containing the controller was running ASP MVC 4, and because they were from different binaries, the controller class could return a
ViewResultin the shadow ofActionResult, but the test project could not convert fromViewResulttoActionResultbecause it's understanding ofViewResultwas different.Although this seems folly because one would assume I would get a build error in this case.
oh well, upgrading fixed it.