本文介绍了如何使用FederatedAuthentication.SessionAuthenticationModule单元测试code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试这个code(登录方法在ASP.NET MVC 4,.NET 4.5的Web应用程序):

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

这是使用此方法SetAuthCookie:

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

在访问时, SessionAuthenticationModule (除了在内部被试图将收购HttpContext的时候提到的物业抛出)我得到一个空引用异常。这是堆栈跟踪:

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()

我已经在位于测试组件和应用程序的正常运行时的code ++工程在app.config使我的web.config的精确拷贝。

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.

我都用了HttpSimulator和MvcContrib测试帮手,使HttpContext的获取设置,但异常仍然抛出。有没有人有一个解决方案或者对如何测试它?一个解决办法

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?

推荐答案

您可以随时使用Typemock隔离/ Telerik的JustMock - 它们使嘲讽静态方法和期货(被你的code内部创建的类)。
在隔离的简单的情况下,
Isolate.WhenCalled(()=&GT; FederatedAuthentication.SessionAuthenticationModule)
.WillReturn(小于一个假值&GT;);

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 simpleIsolate.WhenCalled(() => FederatedAuthentication.SessionAuthenticationModule).WillReturn(<a fake value>);

应该做的伎俩

这篇关于如何使用FederatedAuthentication.SessionAuthenticationModule单元测试code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 01:02