Skip to content

Instantly share code, notes, and snippets.

@elerch
Created November 27, 2013 16:39
Show Gist options
  • Save elerch/7678872 to your computer and use it in GitHub Desktop.
Save elerch/7678872 to your computer and use it in GitHub Desktop.
Code to get a mocked HttpContext for unit testing
private HttpContext GetContext(IEnumerable<KeyValuePair<string,string>> postVariables)
{
postVariables = postVariables ?? Enumerable.Empty<KeyValuePair<string, string>>();
var context = new System.Web.HttpContext(
new System.Web.HttpRequest("", "http://tempuri.org", ""),
new HttpResponse(new StringWriter()));
var sessionContainer = new System.Web.SessionState.HttpSessionStateContainer("id", new System.Web.SessionState.SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
System.Web.SessionState.SessionStateMode.InProc, false);
context.Items["AspSession"] = typeof(System.Web.SessionState.HttpSessionState).GetConstructor(
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
null, System.Reflection.CallingConventions.Standard,
new[] { typeof(System.Web.SessionState.HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
// Make sure forms auth subsystem has initialized
var existingCookieMode = System.Web.Security.FormsAuthentication.CookieMode;
// Now set the internal field to use cookies to avoid NRE
typeof(System.Web.Security.FormsAuthentication).GetField("_CookieMode", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).SetValue(null, System.Web.HttpCookieMode.UseCookies);
context.Request.Browser = new HttpBrowserCapabilities();
context.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };
context.Request.ContentEncoding = System.Text.Encoding.UTF8;
//context.Request.Browser["requiresPostRedirectionHandling"] = "false";
var postType = context.Request.Form.GetType();
postType.GetMethod("MakeReadWrite", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(context.Request.Form, new object[]{}); //hack unto them as they hack unto us.
foreach (var variable in postVariables)
context.Request.Form.Add(variable.Key, variable.Value);
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment