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});

        public void Test_Controller()
            var contentReference = new ContentReference(20);

            var result = Controller.Index(contentReference) as RedirectToRouteResult;

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);


        public void Return_Url_Works()
            const string ReturnUrl = "returnUrl";

            var result =
                new SignUpModel
                    ReturnUrl = ReturnUrl
                as RedirectResult;


submit to reddit

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

Back to top