It appears that something has changed with the release version of MVC4 that is causing the ExecuteResult method in a custom actionresult to not be invoked when the action result is tested from a unit test.
Here is a very contrived example that works in MVC3 and earlier versions of MVC4. Execute result is never “executed” when ran from a unit test. What am i missing here? Anyone else see this behavior?
Action result
public class SomeActionResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("null context");
}
var view = new ViewResult {ViewName = "index"};
view.ExecuteResult(context);
}
}
Controller Action
[HttpPost]
public ActionResult Index(string something)
{
return new SomeActionResult();
}
Unit Test (Using MVCContrib)
[Test]
public void ShouldWork_but_doesnt_in_mvc4()
{
var controller = new HomeController();
var result = controller.Index("test");
result.AssertViewRendered();
}
You must have mistaken something. This won’t work in MVC 3, 2, 1 either. And it is expected. Because a unit test means that you are unit testing something in isolation. So you have one unit test for the controller action and another to test your custom action result.
It is not the
Indexaction that is invoking theExecuteResultresult method on the action result. This happens higher in the MVC execution pipeline during the execution of a user request. In your unit test you are simply calling theIndexmethod.So in order to unit test this controller action you simply assert that it returns an action result of the proper type:
It is in another unit test of the
SomeActionResultthat you will manually invoke the ExecuteResult method and assert that this custom action result used aViewResult.Also it would seem more appropriate to have your custom action result derive from ViewResult rather than manually instantiating a ViewResult inside the ExecuteResult method and setting the ViewName: