How to unit test code that uses FederatedAuthentication.SessionAuthenticationModule

被刻印的时光 ゝ 提交于 2019-12-07 06:54:59

问题


How can I test this code (Login method in a ASP.NET MVC 4, .NET 4.5 web app):

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);
            }
}

that uses this SetAuthCookie method:

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);
}

I get a null reference exception when accessing the SessionAuthenticationModule (the exception is thrown internally by the property mentioned when trying to aquire the HttpContext). This is the stack trace:

   at System.IdentityModel.Services.FederatedAuthentication.GetHttpContextModule[T]()
   at System.IdentityModel.Services.FederatedAuthentication.GetHttpModule[T]()
   at System.IdentityModel.Services.FederatedAuthentication.get_SessionAuthenticationModule()

I have made an exact copy of my web.config in the app.config located in the test assembly and the code works in the normal runtime of the app.

I have used both HttpSimulator and MvcContrib test helper so that the HttpContext gets setup but the exception is still thrown. Does anyone have a solution or a workaround on how to test it?


回答1:


You can always use Typemock Isolator/Telerik JustMock - they enable mocking for static methods and futures (classes that are created inside your code). In case of Isolator a simple Isolate.WhenCalled(() => FederatedAuthentication.SessionAuthenticationModule) .WillReturn(<a fake value>);

should do the trick



来源:https://stackoverflow.com/questions/18744774/how-to-unit-test-code-that-uses-federatedauthentication-sessionauthenticationmod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!