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

标签 c# .net unit-testing asp.net-mvc-4 claims-based-identity

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

相关文章:

c# - 如何获取 MassTransit IBus 的大小(消息数量)?

c# - 从扫描仪(类似键盘)设备获取输入字符串 C# .net

unit-testing - Codeception验收测试不点击按钮

python - 从 TestCase 派生一个类会引发两个错误

python - 如何使用 SQLAlchemy 测试无效记录插入?

C# - 使用 Entity Framework Core 3 HasConversion 将字段转换为 .Net Core 3.1 中的 JSON

c# - 解析空格分隔文本的最佳方法

c# - 在 ASP Net.Core 2.2 中使用自动属性扩展 AnchorTagHelper

c# - .Net - 一般数字格式似乎不保留零

c# - 在哪里可以找到免费、易于实现的 .NET 拼写检查组件?