2011-09-29 29 views
8

BenBir RedirectToAction'ı test etmenin en iyi yolu nedir?

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

gerçek olma aşağıdaki koşul, bu başka bir sayfaya yönlendiriyor var .. bir test yapmak için en iyi ne olurdu?

cevap

14

Bir birim testinde, denetleyiciniz tarafından döndürülen ActionResult belgesini yalnızca doğrulamanız gerekir.

//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

senin birim testinde olası InvalidCastExceptions önlemek için, bu her zaman yapmak budur:

//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"]); 
İlgili konular