Moq: unit testing a method relying on HttpContext

Webforms is notoriously untestable for this exact reason – a lot of code can rely on static classes in the asp.net pipeline.

In order to test this with Moq, you need to refactor your GetSecurityContextUserName() method to use dependency injection with an HttpContextBase object.

HttpContextWrapper resides in System.Web.Abstractions, which ships with .Net 3.5. It is a wrapper for the HttpContext class, and extends HttpContextBase, and you can construct an HttpContextWrapper just like this:

var wrapper = new HttpContextWrapper(HttpContext.Current);

Even better, you can mock an HttpContextBase and set up your expectations on it using Moq. Including the logged in user, etc.

var mockContext = new Mock<HttpContextBase>();

With this in place, you can call GetSecurityContextUserName(mockContext.Object), and your application is much less coupled to the static WebForms HttpContext. If you’re going to be doing a lot of tests that rely on a mocked context, I highly suggest taking a look at Scott Hanselman’s MvcMockHelpers class, which has a version for use with Moq. It conveniently handles a lot of the setup necessary. And despite the name, you don’t need to be doing it with MVC – I use it successfully with webforms apps when I can refactor them to use HttpContextBase.

Leave a Comment