2013-07-08 29 views
3

對於我的單元測試我使用Microsoft.VisualStudio.TestTools.UnitTestingMvcContrib.TestHelper如何從單元測試中的MVC框架中獲取Session.SessionID?

我的控制器操作:

public ActionResult index() 
    { 
     try 
     { 
      Session.Add("username", "Simon"); 
      var lSessionID = Session.SessionID; 

      return Content(lSessionID); 
     } 
     catch 
     { 

     } 

     return Content("false"); 
    } 

我的單元測試:

[TestMethod] 
public void IndexTestMethod1() 
{ 

    TestControllerBuilder builder = new TestControllerBuilder(); 

    StartController controller = new StartController(); 

    builder.InitializeController(controller); 

    var lResult = controller.index(); 

    var lReturn = ((System.Web.Mvc.ContentResult)(lResult)).Content; // returns "false" 

    Assert.IsFalse(lReturn == "false"); 
} 

當我致電index() -action在我的瀏覽器它顯示會話ID。當我通過我的單元測試調用動作時,lReturn"false",而不是預期的會話ID。

如何在我的單元測試中獲取Session.SessionID?

回答

2

Session變量是從ControllerContext.HttpContext.Session中讀取的,Session是HttpSessionStateBase類型的。

在單元測試中,可以使用設置ControllerContext對象。 (或使用任何模擬提供者,如moq)。 我沒有測試的代碼

var contextMock = new Mock<ControllerContext>(); 
var mockHttpContext = new Mock<HttpContextBase>(); 
var session = new Mock<HttpSessionStateBase>(); 
mockHttpContext.Setup(h => h.Session).Returns(session.Object); 
contextMock.Setup(c => c.HttpContext).Returns(mockHttpContext.Object); 
+0

命名空間HttpContextBase找不到 – Simon

+0

您可以添加到System.Web.dll的 – Manas

+0

我加入了命名空間的System.Web參考。但Visual Studio也強調HttpContextBase紅註釋:命名空間HttpContextBase無法找到。我正在使用MVC3 – Simon