2017-01-16 46 views
0

運行我的單元測試方法時,我在HttpSessionStateBase的實例中獲取了空值。我曾經嘲笑像這樣在HttpSessionStateBase中獲取null c#單元測試

var httpRequest = new HttpRequest("", "http://localhost/", ""); 
var stringWriter = new StringWriter(); 
var httpResponse = new HttpResponse(stringWriter); 
var httpContext = new HttpContext(httpRequest, httpResponse); 
var sessionContainer = new HttpSessionStateContainer("id", 
                new SessionStateItemCollection(), 
                new HttpStaticObjectsCollection(), 
                10, 
                true, 
                HttpCookieMode.AutoDetect, 
                SessionStateMode.InProc, 
                false); 

SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer); 

的HttpContext請提出了一些想法,讓在HttpSessionStateBase一些虛擬值

+0

什麼是'SessionStateUtility.AddHttpSessionStateToContext',你到底在哪裏得到空值?請說明你如何試圖訪問你試圖單元測試的實際代碼中的Session對象。 –

+0

public ActionResult Login(Customer obj){Session.Clear(); },此會話的類型爲HttpSessionStateBase –

+0

var result =(RedirectToRouteResult)controller.Login(new Customer(){AdminLogin =「admin」,Password =「admin」}); –

回答

2

讓我們假設你有你需要的單元測試下面的控制器操作:

public class AccountController: Controller 
{ 
    public ActionResult Login(Customer obj) 
    { 
     Session.Clear(); 
     return View(); 
    } 
} 

,這裏是一個樣本線了:

// arrange 
var httpRequest = new HttpRequest("", "http://localhost/", ""); 
var stringWriter = new StringWriter(); 
var httpResponse = new HttpResponse(stringWriter); 
var httpContext = new HttpContext(httpRequest, httpResponse); 
var sessionContainer = new HttpSessionStateContainer(
    "id", 
    new SessionStateItemCollection(), 
    new HttpStaticObjectsCollection(), 
    10, 
    true, 
    HttpCookieMode.AutoDetect, 
    SessionStateMode.InProc, 
    false); 
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer); 

var controller = new AccountController(); 
var requestContext = new RequestContext(new HttpContextWrapper(httpContext), new RouteData()); 
controller.ControllerContext = new ControllerContext(requestContext, controller); 

// act 
var actual = controller.Login(new Customer()); 

// assert 
... 

公告您需要在調用操作之前填充controller.ControllerContext屬性。

+0

偉大的幫助。謝謝各不相同 –

+0

我收到這行錯誤。 FormsAuthentication.SignOut() –

+2

'FormsAuthentication.SignOut'內部依賴於靜態的'HttpContext.Current'屬性。出於顯而易見的原因,這不能在ASP.NET應用程序之外進行單元測試。我建議你在你的門面背後抽象這種硬編碼的依賴關係,然後在控制器中與你的門面一起工作。這將允許您輕鬆地單元測試您的控制器,隔離任何ASP.NET特定的上下文。 –