如何测试此代码(ASP.NET MVC 4、.NET 4.5 网络应用程序中的登录方法):
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);
}
我在访问 SessionAuthenticationModule
时遇到空引用异常(该异常是由尝试获取 HttpContext 时提到的属性在内部抛出的)。这是堆栈跟踪:
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 得到设置,但仍然抛出异常。有没有人有关于如何测试它的解决方案或变通方法?
最佳答案
您始终可以使用 Typemock Isolator/Telerik JustMock - 它们为静态方法和 futures(在您的代码中创建的类)启用模拟。
在隔离器的情况下,一个简单的
Isolate.WhenCalled(() => FederatedAuthentication.SessionAuthenticationModule)
.WillReturn(<a fake value>);
应该可以解决问题
关于c# - 如何对使用 FederatedAuthentication.SessionAuthenticationModule 的代码进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744774/