Unit testing a controller in ASP.NET MVC 2 with RedirectToAction

Posted by Rob Walker on Stack Overflow See other posts from Stack Overflow or by Rob Walker
Published on 2010-03-13T22:00:35Z Indexed on 2010/03/13 22:05 UTC
Read the original article Hit count: 886

Filed under:
|

I have a controller that implements a simple Add operation on an entity and redirects to the Details page:

[HttpPost]
public ActionResult Add(Thing thing)
{ 
  // ... do validation, db stuff ...
  return this.RedirectToAction<c => c.Details(thing.Id));
}

This works great (using the RedirectToAction from the MvcContrib assembly).

When I'm unit testing this method I want to access the ViewData that is returned from the Details action (so I can get the newly inserted thing's primary key and prove it is now in the database).

The test has:

 var result = controller.Add(thing);

But result here is of type: System.Web.Mvc.RedirectToRouteResult (which is a System.Web.Mvc.ActionResult). It doesn't hasn't yet executed the Details method.

I've tried calling ExecuteResult on the returned object passing in a mocked up ControllerContext but the framework wasn't happy with the lack of detail in the mocked object.

I could try filling in the details, etc, etc but then my test code is way longer than the code I'm testing and I feel I need unit tests for the unit tests!

Am I missing something in the testing philosophy? How do I test this action when I can't get at its returned state?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about unittesting