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

にアクセスすると、null 参照例外が発生します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 がセットアップされても例外がスローされるようにしました。誰かがそれをテストする方法に関する解決策または回避策を持っていますか?

4

1 に答える 1

2

Typemock Isolator/Telerik JustMock をいつでも使用できます。静的メソッドとフューチャー (コード内で作成されるクラス) のモックを有効にします。シンプルなアイソレーターの場合 Isolate.WhenCalled(() => FederatedAuthentication.SessionAuthenticationModule) .WillReturn(<a fake value>);

トリックを行う必要があります

于 2014-07-02T06:44:24.043 に答える