Skip to content

Instantly share code, notes, and snippets.

@ScottWeinstein
Created March 22, 2011 17:36
Show Gist options
  • Save ScottWeinstein/881649 to your computer and use it in GitHub Desktop.
Save ScottWeinstein/881649 to your computer and use it in GitHub Desktop.
HttpContextBase for ASP.Net MVC
public static HttpContextBase FakeHttpContext()
{
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>();
request.Setup(req => req.ApplicationPath).Returns("~/");
request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns("~/");
request.Setup(req => req.PathInfo).Returns(string.Empty);
response.Setup(res => res.ApplyAppPathModifier(It.IsAny<string>()))
.Returns((string virtualPath) => virtualPath);
user.Setup(usr => usr.Identity).Returns(identity.Object);
identity.SetupGet(ident => ident.IsAuthenticated).Returns(true);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
return context.Object;
}
@ScottWeinstein
Copy link
Author

-via [http://stackoverflow.com/questions/1228179/mocking-httpcontextbase-with-moq]

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