Skip to content

Instantly share code, notes, and snippets.

@sebnilsson
Created October 24, 2014 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebnilsson/bd0c87da9e6d8af388bc to your computer and use it in GitHub Desktop.
Save sebnilsson/bd0c87da9e6d8af388bc to your computer and use it in GitHub Desktop.
Create a fake HttpContext, without using mocking-frameworks
public static HttpContext GetFakeHttpContext(
string url,
HttpRequest request = null,
HttpResponse response = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
throw new ArgumentOutOfRangeException("url", "The URL must be a well-formed absolute URI.");
}
request = request ?? new HttpRequest(string.Empty, url, null);
response = response ?? new HttpResponse(new System.IO.StringWriter());
var fakeHttpContext = new HttpContext(request, response);
var fakeHttpContextWrapper = new HttpContextWrapper(fakeHttpContext);
request.RequestContext = request.RequestContext
?? new RequestContext(fakeHttpContextWrapper, new RouteData());
return fakeHttpContext;
}
@stevebeauge
Copy link

Isn't a .Dispose missing to clear the StringWriter ?

@sebnilsson
Copy link
Author

@stevebeauge My assumption is that the ASP.NET engine will handle the disposing in its own ways. Given that HttpResponse takes a StringWriter as an argument, I'm hoping that it will also take responsibility for disposing it.

If this was production-code where performance was critical, I would verify these assumptions. Since this is a fake class, used for unit-testing, I will chose not invest that time 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment