Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to test a RedirectToAction?

Tags:

asp.net-mvc

I have the following condition

if (_ldapAuthentication.IsAuthenticated (Domain, login.username, login.PassWord))
{
    _ldapAuthentication.LogOn (indexViewModel.UserName, false);
    _authenticationService.LimpaTentativas (login.username);
    return RedirectToAction ("Index", "Main");
}

being true, it redirects to another page .. what would be best to do a test?

like image 902
Fábio Oliveira Avatar asked Sep 29 '11 18:09

Fábio Oliveira


People also ask

How does RedirectToAction work?

The RedirectToAction() Method This method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts just like as Response. Redirect() in ASP.NET WebForm.

What is difference between redirect and RedirectToAction?

RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.


2 Answers

In a unit test, you'd just assert on the ActionResult returned by your controller.

//Arrange
var controller = new ControllerUnderTest(
                        mockLdap,
                        mockAuthentication
                     );

// Mock/stub your ldap behaviour here, setting up 
// the correct return value for 'IsAuthenticated'.

//Act
RedirectResult redirectResult =
     (RedirectResult) controller.ActionYouAreTesting();

//Assert
Assert.That( redirectResult.Url, Is.EqualTo("/Main/Index"));
like image 110
Dan Avatar answered Nov 03 '22 01:11

Dan


To avoid possible InvalidCastExceptions in your unit test, this is what i always do:

//Arrange
var controller = new ControllerUnderTest(
                        mockLdap,
                        mockAuthentication
                     );

// Mock your ldap behaviour here, setting up 
// the correct return value for 'IsAuthenticated'.

//Act
var result = controller.ActionYouAreTesting() as RedirectToRouteResult;

// Assert
Assert.NotNull(result, "Not a redirect result");
Assert.IsFalse(result.Permanent); // Or IsTrue if you use RedirectToActionPermanent
Assert.AreEqual("Index", result.RouteValues["Action"]);
Assert.AreEqual("Main", result.RouteValues["Controller"]);
like image 20
Filip Cornelissen Avatar answered Nov 03 '22 01:11

Filip Cornelissen