gpt4 book ai didi

c# - 如何对使用 FederatedAuthentication.SessionAuthenticationModule 的代码进行单元测试

转载 作者:太空狗 更新时间:2023-10-29 23:39:24 29 4
gpt4 key购买 nike

如何测试此代码(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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com