How do I Unit Test a MVC redirection?
public ActionResult Create(Product product)
{
_productTask.Save(product);
return RedirectToAction(\"Success\");
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.
[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");
}
}
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.
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"));