Search code examples
asp.net-mvc-3unit-testingmockingmoqhttpcontext

How to mock httpcontext so that it is not null from a unit test?


I am writing a unit test and the controller method is throwing an exception because HttpContext / ControllerContext is null. I don't need to assert anything from the HttpContext, just need it to be not NULL. I have done research and I believe Moq is the answer. But all the samples that I have seen haven't helped me a lot. I don't need to do anything fancy, just to mock the httpcontext. Point me in the right direction!


Solution

  • Got these two functions from here in a class;

    public static class HttpContextFactory
        {
            public static void SetFakeAuthenticatedControllerContext(this Controller controller)
            {
    
                var httpContext = FakeAuthenticatedHttpContext();
                ControllerContext context =
                new ControllerContext(
                new RequestContext(httpContext,
                new RouteData()), controller);
                controller.ControllerContext = context;
    
            }
    
    
            private static HttpContextBase FakeAuthenticatedHttpContext()
            {
                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(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);
                user.Setup(ctx => ctx.Identity).Returns(identity.Object);
                identity.Setup(id => id.IsAuthenticated).Returns(true);
                identity.Setup(id => id.Name).Returns("a.ali174");
    
                return context.Object;
            }
    
    
        }
    

    From the unit test I called them as such;

     HttpContextFactory.SetFakeAuthenticatedControllerContext(controller);
    

    Make sure you have Moq installed in your tests project:

    Install-Package Moq