HttpContext.Current, I hate you.

2013, Mar 28    

What if you have some legacy code that you cannot refactor and that contains references to HttpContext.Current ?

What if you are writing unit tests for your code and it has references to that legacy code?

Option 1: refactor the calls to the legacy code with the proxy pattern and continue writing the tests  (please, do this) .

Option 2: create a fake HttpContext and set it.

If for some reason you’re forced to choose Option 2, here’s an example of how to create a fake HttpContext:

[code lang=”csharp” light=”false”]
var httpRequest = new HttpRequest(filename, domainUrl, null);
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);

SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
[/code]

Did you like this post? Then