Episerver 7 : Unit Testing Redirects In Controllers

Testing RedirectToAction

If you want to unit test your controllers at some stage, you’ll want to test your Action Results. In Epi-Server, it is very likely you may want to Redirect to another episerver page from an MVC controller, e.g. a redirect to any page, after login, or a redirect to the start page.  In order to do this you can still use RedirectToAction with EPiServer, however, you will also need to supply the content reference of the page in the node tag.  Now, you want to unit test your redirect.. how do you do it ?

The below code sample shows how you can achieve this.. please note I’m using FluentAssertions to do the assert checks.

public ActionResult Index(ContentReference contentReference)
{
return RedirectToAction("Index", new {node = contentReference});
}
[TestMethod]
public void Test_Controller()
{
var contentReference = new ContentReference(20);
var result = Controller.Index(contentReference) as RedirectToRouteResult;
result.Should().NotBeNull();
result.RouteValues["action"].ToString().Should().Be("index");
result.RouteValues["node"].ToString().Should().Be(contentReference.ID.ToString());
}

In our test, we return the ActionResult and type it as a ‘RedirectToRouteResult’. After that you can then look in the RouteValues collection for the ‘node’ tag and it should contain the page ID you want to test.

Testing Response.Redirect

In some of your controllers, you may do a complete direct based on a url etc.. to do this you check for a RedirectResult and make sure the url property contains the value you are expecting.

public ActionResult CreateUser(SignUpModel model)
{
if (!string.IsNullOrEmpty(model.ReturnUrl))
return Redirect(model.ReturnUrl);
}
[TestMethod]
public void Return_Url_Works()
{
const string ReturnUrl = "returnUrl";
var result =
Controller.CreateUser(
new SignUpModel
{
ReturnUrl = ReturnUrl
})
as RedirectResult;
result.Url.Should().Be(ReturnUrl);
}

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *