Question

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.

Was it helpful?

Solution

[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");
    }
}

OTHER TIPS

This works for ASP.NET MVC 5 using NUnit:

    [Test]
    public void ShouldRedirectToSuccessAction()
    {
        var controller = new RedirectController();
        var result = controller.Index() as RedirectToRouteResult;

        Assert.That(result.RouteValues["action"], Is.EqualTo("success"));
    }

If you want to test that you are redirecting to a different controller (say NewController), the assertion would be:

Assert.That(result.RouteValues["controller"], Is.EqualTo("New"));

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top