Here is a related discussion.
I stopped referencing HttpContext.Current
directly. and use this class instead ( See this blog ):
public class HttpContextFactory
{
private static HttpContextBase m_context;
public static HttpContextBase Current
{
get
{
if (m_context != null)
return m_context;
if (HttpContext.Current == null)
throw new InvalidOperationException("HttpContext not available");
return new HttpContextWrapper(HttpContext.Current);
}
}
public static void SetCurrentContext(HttpContextBase context)
{
m_context = context;
}
}
and use HttpContextFactory.Current
instead of HttpContext.Current
in our code.
Then you write this in your test:
HttpContextFactory.SetCurrentContext(GetMockedHttpContext());
where GetMockedHttpContext() is from here and looks like this:
private System.Web.HttpContextBase GetMockedHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Expect(ctx => ctx.Request).Returns(request.Object);
context.Expect(ctx => ctx.Response).Returns(response.Object);
context.Expect(ctx => ctx.Session).Returns(session.Object);
context.Expect(ctx => ctx.Server).Returns(server.Object);
context.Expect(ctx => ctx.User).Returns(user.Object);
user.Expect(ctx => ctx.Identity).Returns(identity.Object);
identity.Expect(id => id.IsAuthenticated).Returns(true);
identity.Expect(id => id.Name).Returns("test");
return context.Object;
}
It uses a mocking framework called moq
In your test project you have to add a reference to System.Web
and System.Web.Abstractions
, where HttpContextBase
is defined.