.Net MVC testing controller HTTPContext

Here’s a way to test for HTTPContext in a MVC controller:

[Test]
public void TestController_HasContext_ContextNotNull()
{
   var controller = new TestController();

   var server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose);
   var response = new Mock<HttpResponseBase>(MockBehavior.Strict);

   var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
   request.Setup(r => r.UserHostAddress).Returns("127.0.0.1");

   var session = new Mock<HttpSessionStateBase>();
   session.Setup(s => s.SessionID).Returns(Guid.NewGuid().ToString());

   var context = new Mock<HttpContextBase>();
   context.SetupGet(c => c.Request).Returns(request.Object);
   context.SetupGet(c => c.Response).Returns(response.Object);
   context.SetupGet(c => c.Server).Returns(server.Object);
   context.SetupGet(c => c.Session).Returns(session.Object);

   controller.ControllerContext = new ControllerContext(context.Object,
                    new RouteData(), controller);

   Assert.IsNotNull(controller.HttpContext);
}

Leave a Reply

Your email address will not be published. Required fields are marked *