利用 HttpContext.Current.Session 的单元测试代码
问题:
尝试时为了对 Web 服务进行单元测试,我在设置时遇到空引用异常HttpContext.Current.Session 值。尽管使用 SimpleWorkerRequest 创建上下文,HttpContext.Current.Session 仍然为空。如何在单元测试中初始化当前会话?
答案:
要模拟 HttpContext 及其会话对象,您可以采用以下两种方法之一:
使用反射:
<br>public static HttpContext FakeHttpContext()<br>{<br> var httpRequest = new HttpRequest("", "http://example.com/" , "");<br> var stringWriter = new StringWriter();<br> var httpResponse = new HttpResponse(stringWriter);<br> var httpContext = new HttpContext(httpRequest, httpResponse);<p>var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),</p><pre class="brush:php;toolbar:false"> 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;
}
使用SessionStateUtility:
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);<br>
一旦你有创建了模拟 HttpContext,您可以将其设置为您的单元的当前上下文测试:
<br>HttpContext.Current = MockHelper.FakeHttpContext();<br>
以上是如何模拟 HttpContext.Current.Session 进行单元测试?的详细内容。更多信息请关注PHP中文网其他相关文章!