Skip to content

Instantly share code, notes, and snippets.

@thoemmi
Forked from AlexZeitler/fake-http-context.cs
Created October 5, 2012 19:59
Show Gist options
  • Save thoemmi/3842014 to your computer and use it in GitHub Desktop.
Save thoemmi/3842014 to your computer and use it in GitHub Desktop.
A Moq-using fake HTTP context to test controllers.
public HttpContextBase FakeHttpContext() {
var context = new Mock<HttpContextBase>();
var files = new Mock<HttpFileCollectionBase>();
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);
request.Setup(req => req.Form).Returns(new NameValueCollection());
request.Setup(req => req.QueryString).Returns(new NameValueCollection());
request.Setup(req => req.Files).Returns(files.Object);
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment