Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test code that uses FederatedAuthentication.SessionAuthenticationModule

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?

like image 695
Liviu Mandras Avatar asked Nov 02 '22 14:11

Liviu Mandras


1 Answers

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

like image 146
Dror Helper Avatar answered Nov 15 '22 06:11

Dror Helper