Asp.net-Mvc
HttpContext 中需要什麼來允許 FormsAuthentication.SignOut() 執行?
我正在嘗試為我們的註銷方法編寫一個單元測試。除其他外
FormsAuthentication.SignOut()。但是,它會拋出一個System.NullReferenceException.我創建了一個模擬;
HttpContext(使用起訂量),但它顯然缺少一些東西。我的模擬上下文包含:
HttpRequestBase一個嘲笑RequestHttpResponseBase一個嘲笑Response- 一個
HttpCookieCollection開一個Request.Cookies又一個開Response.CookiesIPrincipal一個嘲笑User我知道我可以走包裝器路線並
FormsAuth在其位置注入一個空包裝器對象,但我真的很想避免使用 3 個附加文件來修復一行程式碼。那我仍然很好奇答案所以我的問題是“允許****什麼
HttpContext``FormsAuthentication.SignOut() to execute.”
在這種情況下,NullReferenceException 實際上是由呼叫拋出的:
current.Request.Browser["supportsEmptyStringInCookieValue"]你可以通過呼叫來測試這個斷言:
HttpContext.Current.Request.Browser.SupportsEmptyStringInCookieValue…這也將返回 NullReferenceException。與接受的答案相反,如果您嘗試致電:
CookielessHelperClass.UseCookieless(current, false, CookieMode)…從即時視窗,這將返回沒有錯誤。
您可以像這樣修復異常:
HttpContext.Current.Request.Browser = new HttpBrowserCapabilities() { Capabilities = new Dictionary<string, string> { { "supportsEmptyStringInCookieValue", "false" } } };…
FormsAuthentication.SignOut()現在通話將成功。
您始終可以將 FormsAuthentication.SignOut() 包裝到另一個方法中並存根/模擬它。
創建 IFormsAuthenticationWrap 介面。
public interface IFormsAuthenticationWrap { void SignOut(); }創建實現 IFormsAuthenticationWrap 的包裝類
public class FormsAuthenticationWrap : IFormsAuthenticationWrap { public void SignOut() { FormsAuthentication.SignOut(); } }您的呼叫類將如下所示:
public class LogOutClass { private readonly IFormsAuthenticationWrap _formsAuthentication; public LogOutClass() : this (new FormsAuthenticationWrap()) { } public LogOutClass(IFormsAuthenticationWrap formsAuthentication) { _formsAuthentication = formsAuthentication; } public void LogOutMethod() { // Code before SignOut _formsAuthentication.SignOut(); // Code after SignOut } }現在讓我們開始測試。您可以使用 Moq 存根/模擬,但我將在這裡展示如何手動完成。創建你的存根/模擬類:
public class FormsAuthenticationStub : IFormsAuthenticationWrap { public void SignOut() { } }最後寫測試:
[TestMethod] public void TestLogOutMethod() { var logOutClass = new LogOutClass(new FormsAuthenticationStub()); logOutClass.LogOutMethod(); }