如何在单元测试中从MVC框架中获取Session.SessionID

本文关键字:框架 获取 Session SessionID MVC 单元测试 | 更新日期: 2023-09-27 18:21:21

对于我的单元测试,我使用Microsoft.VisualStudio.TestTools.UnitTestingMvcContrib.TestHelper

我在控制器中的操作:

    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()-操作时,它会显示会话ID。当我通过单元测试调用操作时,lReturn"false",而不是预期的Session-ID。

如何在单元测试中获得Session.SessionID?

如何在单元测试中从MVC框架中获取Session.SessionID

会话变量是从ControllerContext.HttpContext.Session中读取的,会话的类型为HttpSessionStateBase。

在单元测试中,可以使用set来设置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);