15

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?

2 Answers 2

26

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");
Sign up to request clarification or add additional context in comments.

1 Comment

This MvcContrib library is fantastic!
11

Try this...

var result = sut.Create(newProduct) as RedirectToRouteResult;
Assert.Equal(result.RouteValues["action"], "Index");

And if you are passing a parameter in redirection you can do something like this...

var result = sut.Create(newProduct) as RedirectToRouteResult;
Assert.Equal(result.RouteValues["action"], "Index");
Assert.Equal(result.RouteValues["Parameter Name"], "Parameter Value");

Hope this helps :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.