Using Moq to mock ASP.NET MVC HttpContextBase

Here’s my little example about how to use Moq to mock HttpContextBase and it’s members to make controller tests pass. You can use this code when you are not allowed to use open-source or use-on-your-own-risk pieces of software that provide you this kind on initialization using built-in features. Also it is good exercise that introduces you how to solve mocking problems.

Here’s the simple example to get started.

var controller = new MyController();

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

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

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
new RouteData(), controller);

Same way you can also mock other members of HttpContextBase.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    6 thoughts on “Using Moq to mock ASP.NET MVC HttpContextBase

    • July 16, 2011 at 1:54 pm


      Nice post. Good timing :) was just thinking about how to do this.

      So your Mocking the HttpContextBase without a creating a wrapper for it? Do you have a larger example available maybe a sample project that has the controller code?


    • August 4, 2011 at 1:00 pm

      What is the ControllerContext ? And the namespace ?

      re: new ControllerContext(context.Object,
      new RouteData(), controller);

    • August 4, 2011 at 1:06 pm

      Do you have an example of how to use this code ?

    • January 18, 2012 at 5:05 pm

      Hi, thanks for this sample, was just what I needed.

      @Zeb: Just instantiate your own controller in the first line, and remember to add the System.Web.Routing namespace in your using statements.

    • December 15, 2015 at 5:47 am

      Nice and concise, but some explanation of your choices of strict mocks for some types and loose mocks for other types would be very helpful.

    • June 14, 2017 at 7:16 pm

      Unfortunately, this does not work in core 1.1. Any ideas on how to do it?

    Leave a Reply

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