The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
The property stores the HttpContext instance that applies to the current request. The properties of this instance are the non-static properties of the HttpContext class. You can also use the Page. Context property to access the HttpContext object for the current HTTP request.
In the editor, click an action indicator next to a test or test class , and then choose Create New Session in the action list. A new session with this test/test class will be created. In the Unit Tests window, select tests/test classes for the new session and choose Create New Session.
HttpContext is a type which has a static Current property that you're using to get the current context. There isn't a System. Web. Mvc.
HttpContext.Current
returns an instance of System.Web.HttpContext
, which does not extend System.Web.HttpContextBase
. HttpContextBase
was added later to address HttpContext
being difficult to mock. The two classes are basically unrelated (HttpContextWrapper
is used as an adapter between them).
Fortunately, HttpContext
itself is fakeable just enough for you do replace the IPrincipal
(User) and IIdentity
.
The following code runs as expected, even in a console application:
HttpContext.Current = new HttpContext(
new HttpRequest("", "http://tempuri.org", ""),
new HttpResponse(new StringWriter())
);
// User is logged in
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity("username"),
new string[0]
);
// User is logged out
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity(String.Empty),
new string[0]
);
Below Test Init will also do the job.
[TestInitialize]
public void TestInit()
{
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
YourControllerToBeTestedController = GetYourToBeTestedController();
}
I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.
I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.
Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.
I generally do something like this:
public static class FakeHttpContext
{
public static void SetFakeContext(this Controller controller)
{
var httpContext = MakeFakeContext();
ControllerContext context =
new ControllerContext(
new RequestContext(httpContext,
new RouteData()), controller);
controller.ControllerContext = context;
}
private static HttpContextBase MakeFakeContext()
{
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.Setup(c=> c.Request).Returns(request.Object);
context.Setup(c=> c.Response).Returns(response.Object);
context.Setup(c=> c.Session).Returns(session.Object);
context.Setup(c=> c.Server).Returns(server.Object);
context.Setup(c=> c.User).Returns(user.Object);
user.Setup(c=> c.Identity).Returns(identity.Object);
identity.Setup(i => i.IsAuthenticated).Returns(true);
identity.Setup(i => i.Name).Returns("admin");
return context.Object;
}
}
And initiating the context like this
FakeHttpContext.SetFakeContext(moController);
And calling the Method in the controller straight forward
long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);
If your application third party redirect internally, so it is better to mock HttpContext in below way :
HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With