Mocking HttpContextBase with Moq

I’m using a version of some code Steve Sanderson included in his Pro Asp.NET MVC book… and I’m currently having a moral dilemma whether it’s okay to post the code here. How about I compromise with a highly stripped down version? 😉

So this can easily be reused, create a class similar to the one below that you will pass your controller. This will set up your mocks and set them to your controller’s ControllerContext

public class ContextMocks
{
    public Moq.Mock<HttpContextBase> HttpContext { get; set; }
    public Moq.Mock<HttpRequestBase> Request { get; set; }
    public RouteData RouteData { get; set; }

    public ContextMocks(Controller controller)
    {
        //define context objects
        HttpContext = new Moq.Mock<HttpContextBase>();
        HttpContext.Setup(x => x.Request).Returns(Request.Object);
        //you would setup Response, Session, etc similarly with either mocks or fakes

        //apply context to controller
        RequestContext rc = new RequestContext(HttpContext.Object, new RouteData());
        controller.ControllerContext = new ControllerContext(rc, controller);
    }
}

And then in your test method you’d just create an instance of ContextMocks and pass in the controller object you’re testing:

[Test]
Public void test()
{
     var mocks = new ContextMocks(controller);
     var req = controller.Request; 
     //do some asserts on Request object
}

Seems very similar to Craig’s examples, but this is with Moq v3. I have to give props to Steve Sanderson for this – I’m using this as a basis for testing all kinds of otherwise traditionally hard-to-test stuff: cookies, session, request method, querystring and more!

Leave a Comment