Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify redirect with unit test in asp.net mvc

Is there an easy way to verify in a unit test that a controller action is indeed redirecting to a specific page?

Controller code:

public ActionResult Create(ProductModel newProduct)
{
    this.repository.CreateProduct(newProduct);
    return RedirectToAction("Index");
}

So in my test, I would need to verify that the controller is actually redirecting.

ProductController controller = new ProductController(repository);

RedirectToRouteResult result = (RedirectToRouteResult)controller.Create(newProduct);

bool redirected = checkGoesHere;
Assert.True(redirected, "Should have redirected to 'Index'");

I'm just not sure how to do the verification. Any ideas?

like image 648
Spectre87 Avatar asked Jul 15 '12 19:07

Spectre87


1 Answers

Sure:

Assert.AreEqual("Index", result.RouteValues["action"]);
Assert.IsNull(result.RouteValues["controller"]); // means we redirected to the same controller

and using MvcContrib.TestHelper you could write this unit test in a much more elegant way (you don't even need to cast to a RedirectToRouteResult):

// arrange
var sut = new ProductController(repository);

// act
var result = sut.Create(newProduct);

// assert
result
    .AssertActionRedirect()
    .ToAction("Index");
like image 140
Darin Dimitrov Avatar answered Sep 23 '22 12:09

Darin Dimitrov