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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With