2011-09-29 62 views
8

我有以下條件什麼是測試RedirectToAction的最佳方式?

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

是真實的,它重定向到另一個頁面..什麼是最好做一個測試?

回答

14

在單元測試中,您只需在控制器返回的ActionResult上聲明。

//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")); 
9

爲避免你的單元測試可能InvalidCastExceptions,這就是我總是這樣:

//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"]); 
相關問題