# IT:AD:Unit Testing/Automated:HowTo:Mock HttpContext # * [[../|(UP)]] {{indexmenu>.#2|nsort tsort}} I usually forget how to set up tricky unit tests... ## Notes ## Here are some examples to jog my memory. ### Web ### [Category("API")] [Test] [Bootstrap] public void SetHttpContextQuery2() { var url = "http://foo.bar/someHandler.ashx"; HttpContext.Current = HttpContextHelper.FakeHttpContext(url, "wada=woo"); //IMPORTANT: //To Match running conditions, have to put QueryString as part of url AS WELL as in second arg. //See 1 and 2, compared to 3 which finally matches run time values: var r = HttpContext.Current.Request; //Shows that Url is not equal to runtime (url would include the query string) Assert.AreEqual(new Uri(url), r.Url); Assert.AreEqual("/someHandler.ashx?wada=woo", r.RawUrl); Assert.AreEqual("/someHandler.ashx", r.Path); Assert.IsTrue(r.QueryString.Count > 0); } The above is using (which can be also found in [[Projects/XActLib/]] of course): /// Usage /// HttpContext.Current = HttpContextHelper.FakeHttpContext(); /// See: http://stackoverflow.com/a/10126711/1052767 public static HttpContext FakeHttpContext(string url = "http://fake.env/", string queryString = "", string fileName = "") { var httpRequest = new HttpRequest(fileName, url, queryString); 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; }