c# - 在单元测试中设置 HttpContext.Current.Session

标签 c# web-services unit-testing httpcontext

我有一个网络服务,我正在尝试对其进行单元测试。在服务中,它从 HttpContext 中提取几个值,如下所示:

 m_password = (string)HttpContext.Current.Session["CustomerId"];
 m_userID = (string)HttpContext.Current.Session["CustomerUrl"];

在单元测试中,我使用简单的工作请求创建上下文,如下所示:

SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;

但是,每当我尝试设置 HttpContext.Current.Session

的值时
HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";

我收到空引用异常,提示 HttpContext.Current.Session 为空。

有什么方法可以在单元测试中初始化当前 session 吗?

最佳答案

您可以像这样创建一个新的 HttpContext 来“伪装”它:

http://www.necronet.org/archive/2010/07/28/unit-testing-code-that-uses-httpcontext-current-session.aspx

我已经采用该代码并将其放在静态帮助程序类中,如下所示:

public static HttpContext FakeHttpContext()
{
    var httpRequest = new HttpRequest("", "http://example.com/", "");
    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);

    httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                BindingFlags.NonPublic | BindingFlags.Instance,
                                null, CallingConventions.Standard,
                                new[] { typeof(HttpSessionStateContainer) },
                                null)
                        .Invoke(new object[] { sessionContainer });

    return httpContext;
}

或者不使用反射来构造新的 HttpSessionState 实例,您可以将 HttpSessionStateContainer 附加到 HttpContext(根据 Brent M . Spell 的评论):

SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);

然后您可以在单元测试中调用它,例如:

HttpContext.Current = MockHelper.FakeHttpContext();

关于c# - 在单元测试中设置 HttpContext.Current.Session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9624242/

相关文章:

c# - 将泛型 Span<T> 转换为特定实例化(例如 Span<int>)(如果它在运行时实际上属于该类型)

c# - Winform Webbrowser 被识别为移动设备

c# - 设置 Session.Timeout 或将其添加到 web.config 之间有区别吗?

javascript - ajax post带有参数500服务器未找到错误

Java Web 服务客户端问题(Axis Error-(403)Forbidden)

java - Easymock 不兼容的返回值类型错误

c# - 将测试方法放在您正在测试的同一个类中有什么问题吗?

c# - 如何简化 href 属性,这样我就不会得到 "the given paths format is not supported"?

java - hamcrest 中的递归 SamePropertyValuesAs 匹配器

web-services - 使用 Caddy 的 Web 套接字 (WSS) 反向代理