Mock HttpContext.Current in Test Init Method [c#]


Below Test Init will also do the job.

public void TestInit()
  HttpContext.Current = new HttpContext(new HttpRequest(null, "", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();


I'm trying to add unit testing to an ASP.NET MVC application I have built. In my unit tests I use the following code:

public void IndexAction_Should_Return_View() {
    var controller = new MembershipController();


With the following helpers to mock the controller context:

public static class FakeControllerContext {
    public static HttpContextBase FakeHttpContext(string username) {
        var context = new Mock<HttpContextBase>();

        context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));

        if (!string.IsNullOrEmpty(username))
            context.SetupGet(ctx => ctx.User.Identity).Returns(FakeIdentity.CreateIdentity(username));

        return context.Object;

    public static void SetFakeControllerContext(this Controller controller, string username = null) {
        var httpContext = FakeHttpContext(username);
        var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
        controller.ControllerContext = context;

This test class inherits from a base class which has the following:

public void Init() {

Inside this method it calls a library (which i have no control over) which tries to run the following code:


Now you can probably see the problem. I have set the fake HttpContext against the controller but not in this base Init method. Unit testing / mocking is very new to me so I want to make sure I get this right. What is the correct way for me to Mock out the HttpContext so that it is shared across my controller and any libraries which are called in my Init method.

Microsoft Fakes HttpContext.User.Identity

In order for me to stub the IPrincipal I had to fake System which in turn added mscorlib.fakes as well. This then enabled me to use System.Security.Principal.Fakes.StubIPrincipal in my code.

I then stubbed User.Identity.Name by doing the following:

using (AccountController controller = new AccountController())
    StubHttpContextBase stubHttpContext = new StubHttpContextBase();

    controller.ControllerContext = new ControllerContext(stubHttpContext, new RouteData(), controller);

    StubIPrincipal principal = new StubIPrincipal();
    principal.IdentityGet = () =>
        return new StubIIdentity 
            NameGet = () => "bob" 
    stubHttpContext.UserGet = () => principal;

HttpContext.Current always null when sending request from unit test

Unit testing is not the same as calling your api through a web client.

When you are using a web client, you api is running in the context of you web server (IIS, for example) and the web server will provide the system with che "current" HttpContext.

If you call you code plain and simple from a unit test method you're not running in the context of a web server, but you're calling it simply as a method of a class. Obviously you can do it, but you need to "mock" (of fake, if you want) the current HttpContext to simulate you're running in a real web server.

Check this SO answer for the details on how to do it.

BTW, this is not the case when you run integration tests (means calling the real API throught a web client and just check the input-output results): in that case you are running your real code in a real context and everything will work fine.

How to create unit test with HttpContext for authorization inside a method?

HttpContext.Current is static and can be assigned:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "", ""),
    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]

Code from Mock HttpContext.Current in Test Init Method