ASP.NET MVC unit test controller with HttpContext

Unless you use Typemock or Moles, you can’t.

In ASP.NET MVC you are not supposed to be using HttpContext.Current. Change your base class to use ControllerBase.ControllerContext – it has a HttpContext property that exposes the testable HttpContextBase class.

Here’s an example of how you can use Moq to set up a Mock HttpContextBase:

var httpCtxStub = new Mock<HttpContextBase>();

var controllerCtx = new ControllerContext();
controllerCtx.HttpContext = httpCtxStub.Object;

sut.ControllerContext = controllerCtx;

// Exercise and verify the sut

where sut represents the System Under Test (SUT), i.e. the Controller you wish to test.

Leave a Comment