在 HttpSessionStateBase c# 单元测试中获取 null

Getting null in HttpSessionStateBase c# unit test

虽然 运行 我的单元测试方法,但我在 HttpSessionStateBase 的实例中得到空值。我像这样嘲笑了 httpcontext

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

请提出一些想法以在 HttpSessionStateBase 中获取一些虚拟值

假设您有以下控制器操作需要进行单元测试:

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

这是一个示例 wire-up:

// 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 属性。