Skip to content

Instantly share code, notes, and snippets.

@lkaczanowski
Created November 30, 2012 07:23
Show Gist options
  • Save lkaczanowski/4174294 to your computer and use it in GitHub Desktop.
Save lkaczanowski/4174294 to your computer and use it in GitHub Desktop.
Creates HttpContext with Session to stub HttpContext.Current
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
using NUnit.Framework;
namespace Mvc.Tests
{
[TestFixture]
public class HttpContextCurrentTests
{
private HttpSessionState _sessionState;
[SetUp]
public void SetUp()
{
HttpContext.Current = CreateHttpContextCurrent();
_sessionState = HttpContext.Current.Session;
}
private HttpContext CreateHttpContextCurrent()
{
var httpRequest = new HttpRequest(string.Empty, "http://someurl/", string.Empty);
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
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;
}
}
}
@drozdik-m
Copy link

God bless

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment