views:

695

answers:

4

How do I Unit Test a MVC redirection?

    public ActionResult Create(Product product)
    {

        _productTask.Save(product);

        return RedirectToAction("Success");

    }

    public ActionResult Success()
    {

        return View();
    }

Is Ayende's approach still the best way to go, with preview 5:

 public static void RenderView(this Controller self, string action) 
 {
    typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} ); 
 }

Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.

A: 

Funnily enough, I was reading about this last night at http://www.asp.net/learn/mvc/tutorial-07-cs.aspx

harriyott
A: 

You can assert on the ActionResult that is returned, you'll need to cast it to the appropriate type but it does allow you to use state-based testing. A search on the Web should find some useful links, here's just one though.

+8  A: 
[TestFixture]
public class RedirectTester
{
 [Test]
 public void Should_redirect_to_success_action()
 {
  var controller = new RedirectController();
  var result = controller.Index() as RedirectToRouteResult;
  Assert.That(result, Is.Not.Null);
  Assert.That(result.Values["action"], Is.EqualTo("success"));
 }
}

public class RedirectController : Controller
{
 public ActionResult Index()
 {
  return RedirectToAction("success");
 }
}
Matt Hinze
RedirectToRouteResult.Values[] is now RedirectToRouteResult.RouteValues[...]
mxmissile
does anyone know how you can actually have the action invoked when redirected during testing ?
f0ster
@f0ster Why would you want that? Either way, `controller.Success()` in the above example would accomplish this.
bzlm
A: 

you can use Mvc.Contrib.TestHelper which provides assertions for testing redirections. Take a look at http://kbochevski.blogspot.com/2010/06/unit-testing-mvcnet.html and the code sample. It might be helpful.

hurbata