测试RedirectToAction的最佳方法是什么?

时间:2011-09-29 18:48:20

标签: asp.net-mvc

我有以下条件

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

是真的,它会重定向到另一个页面..最好做一个测试?

2 个答案:

答案 0 :(得分:16)

在单元测试中,您只需断言控制器返回的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"));

答案 1 :(得分:9)

为了避免单元测试中出现可能的InvalidCastException,这就是我经常做的事情:

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