C# – How to mock the HttpContext in ASP.NET MVC using Moq

asp.net-mvcchttpcontextmockingmoq

[TestMethod]
public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    context
        .Setup(c => c.Request)
        .Returns(request.Object);
    HomeController controller = new HomeController();

    controller.HttpContext = context; //Here I am getting an error (read only).
    ...
 }

my base controller has an overrride of the Initialize that get's this requestContext. I am trying to pass this along but I am not doing something right.

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
}

Where can I get more information on mocking my RequestContext and HttpContext using Moq? I am trying to mock cookies and the general context.

Best Answer

HttpContext is read-only, but it is actually derived from the ControllerContext, which you can set.

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