Created
September 10, 2012 22:46
-
-
Save jarrettmeyer/3694509 to your computer and use it in GitHub Desktop.
Sample code to run an in-memory HTTP context for unit testing in .NET
This file contains 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
internal class HttpTest | |
{ | |
private static HttpContext httpContext; | |
private static HttpWorkerRequest httpWorkerRequest; | |
private static StringBuilder outputStringBuilder; | |
private static TextWriter output; | |
private static NameValueCollection httpHeaders; | |
private static HttpCookieCollection requestCookies; | |
private static HttpCookieCollection responseCookies; | |
public static HttpContext HttpContext | |
{ | |
get { return httpContext; } | |
} | |
public static string Output | |
{ | |
get { return outputStringBuilder.ToString(); } | |
} | |
public static void AddAjaxRequestHeader() | |
{ | |
AddHttpHeader("X-Requested-With", "XMLHttpRequest"); | |
} | |
public static void AddHttpHeader(string name, string value) | |
{ | |
if (httpHeaders == null) | |
{ | |
httpHeaders = new NameValueCollection(); | |
} | |
httpHeaders.Add(name, value); | |
} | |
public static void DestroyHttpContext() | |
{ | |
HttpContext.Current = null; | |
httpHeaders = null; | |
requestCookies = null; | |
responseCookies = null; | |
} | |
public static void SetUpHttpContext(string page = "/default.aspx") | |
{ | |
BuildResponseOutput(); | |
BuildHttpWorkerRequest(page); | |
BuildHttpContext(); | |
BuildHttpSession(); | |
} | |
private static void BuildHttpContext() | |
{ | |
httpContext = new HttpContext(httpWorkerRequest); | |
HttpContext.Current = httpContext; | |
} | |
private static void BuildHttpSession() | |
{ | |
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required); | |
var sessionStateContainer = new HttpSessionStateContainer(Guid.NewGuid().ToString(), new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true, HttpCookieMode.UseCookies, SessionStateMode.Off, false); | |
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionStateContainer); | |
} | |
private static void BuildHttpWorkerRequest(string page) | |
{ | |
const string appVirtualDir = "/"; | |
const string appPhysicalDir = @"c:\"; | |
string query = string.Empty; | |
httpWorkerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output); | |
} | |
private static void BuildResponseOutput() | |
{ | |
outputStringBuilder = new StringBuilder(); | |
output = new StringWriter(outputStringBuilder); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment