[c#] How do I mock the HttpContext in ASP.NET MVC using Moq?

1 Answers

Create a request, response and put them both to HttpContext:

HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist()
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
        .Setup(c => c.Request)
    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)

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

Here is an example of how you can set this up: Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq)

Note the extension methods which really help to simplify the usage of this mocking classes:

var mockHttpContext = new API_Moq_HttpContext();

var httpContext = mockHttpContext.httpContext();

httpContext.request_Write("   this is a web page".line());  

return httpContext.request_Read();

Here is an example of how to write a Unit Test using moq to check that an HttpModule is working as expected: Unit Test for HttpModule using Moq to wrap HttpRequest

Update: this API has been refactored to