如何测试这段代码(ASP.NET MVC 4,.NET 4.5 Web应用程序中的登录方法):
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && _userCredentialsService.ValidateUser(model.UserName, model.Password))
{
SessionAuthentication.SetAuthCookie(model.UserName, _userCredentialsService.GetUserGroups(model.UserName), model.RememberMe);
return RedirectToLocal(returnUrl);
}
}
使用SetAuthCookie方法的代码:
public static void SetAuthCookie(IEnumerable<Claim> claims, bool isPersistent)
{
if (!HttpContext.Current.Request.IsSecureConnection && FormsAuthentication.RequireSSL)
{
throw new HttpException(500, "Connection is not secured with SSL");
}
var sessionToken = CreateSessionSecurityToken(CreatePrincipal(claims.ToList()), isPersistent);
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken);
}
当试图获取HttpContext时,访问SessionAuthenticationModule时引发了空引用异常(这个属性内部抛出了异常)。以下是堆栈跟踪:
at System.IdentityModel.Services.FederatedAuthentication.GetHttpContextModule[T]()
at System.IdentityModel.Services.FederatedAuthentication.GetHttpModule[T]()
at System.IdentityModel.Services.FederatedAuthentication.get_SessionAuthenticationModule()
我已经在测试程序集的app.config中创建了一个web.config的精确副本。代码在应用程序的正常运行时工作。
我使用了HttpSimulator和MvcContrib测试助手,以便设置HttpContext,但仍然会抛出异常。是否有人能提供解决方案或绕过方法来进行测试?