Forked from lkaczanowski/HttpContextCurrentTests.cs
Created
January 24, 2022 08:02
-
-
Save uzbekdev1/43e45782e58121ec8202b0f41aae7b55 to your computer and use it in GitHub Desktop.
Creates HttpContext with Session to stub HttpContext.Current
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment