it:ad:unit_testing:automated:howto:mock_httpcontext

IT:AD:Unit Testing/Automated:HowTo:Mock HttpContext

Here are some examples to jog my memory.

        [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;
}

  • /home/skysigal/public_html/data/pages/it/ad/unit_testing/automated/howto/mock_httpcontext.txt
  • Last modified: 2023/11/04 02:31
  • by 127.0.0.1