Testing Action Results with ASP.NET MVC

The latest preview of ASP.NET MVC supports returning ActionResult objects from controller actions.

This makes it very easy to test the results of an action (for example, redirecting to another controller) which was a much more involved process in previous releases.

Imagine the following controller:

public class HomeController : Controller {
	public ActionResult Index() {
		return RedirectToAction(new { controller = "Home", action = "about" });
	}
 
	public ActionResult About() {
		return RenderView();
	}
}

While previously you'd have to mock the Response.Redirect method, now you can do this:

var controller = new HomeController();
ActionRedirectResult result = controller.Index() as ActionRedirectResult;
 
if(result == null) {
	Assert.Fail("Expected an ActionRedirectResult");
}
else {
	Assert.That(result.Values["controller"], Is.EqualTo("Home"));
	Assert.That(result.Values["action"], Is.EqualTo("about"));
}

While this is certainly easier, it is still a little cumbersome. To help with this, I've added some extension methods to MvcContrib's 'TestHelper' project. So now I can write:

var controller = new HomeController();
controller.Index().AssertIsActionRedirect().ToController("Home").ToAction("about");

Much better!

Written on April 19, 2008