Skip to content

Instantly share code, notes, and snippets.

@andrewrjones
Created February 7, 2012 13:32
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 andrewrjones/1759688 to your computer and use it in GitHub Desktop.
Save andrewrjones/1759688 to your computer and use it in GitHub Desktop.
Factory method to allow us to mock HttpContext when testing
using System.Web;
namespace AndrewJones
{
/// <summary>
/// Factory method to allow us to mock HttpContext when testing
/// </summary>
public static class HttpContextFactory
{
private static HttpContextBase mockHttpContext;
/// <summary>
/// Sets the HttpContext. Used for mocking.
/// </summary>
/// <param name="httpContextBase">A HttpContextBase object</param>
public static void SetHttpContext(HttpContextBase httpContextBase)
{
mockHttpContext = httpContextBase;
}
/// <summary>
/// Sets the HttpContext to null.
/// </summary>
public static void ResetHttpContext()
{
mockHttpContext = null;
}
/// <summary>
/// Returns a previously set HttpContext, or the current HttpContext
/// </summary>
public static HttpContextBase GetHttpContext()
{
if (mockHttpContext != null)
{
return mockHttpContext;
}
if (HttpContext.Current != null)
{
return new HttpContextWrapper(HttpContext.Current);
}
return null;
}
}
}
@YoungjaeKim
Copy link

thanks 👍

@Jacob-McKay
Copy link

Thanks @andrewrjones

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