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

5

如何测试这段代码(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,但仍然会抛出异常。是否有人能提供解决方案或绕过方法来进行测试?
1个回答

2
您可以始终使用Typemock Isolator / Telerik JustMock - 它们可以为静态方法和futures(在您的代码中创建的类)启用模拟。 在Isolator的情况下,简单的 Isolate.WhenCalled(() => FederatedAuthentication.SessionAuthenticationModule) .WillReturn(<a fake value>); 就可以解决问题。

我本来希望有一个“免费”的东西。也许是微软的Moles。无论如何,我还是要为这个想法点赞。通常我不喜欢这种嘲讽方式,但在这种情况下这可能是最好/最简单的方法。 - Liviu Mandras

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接