Mocking HttpContext in .NET MVC2 using Moq

Posted by Richard on Stack Overflow See other posts from Stack Overflow or by Richard
Published on 2010-04-07T22:55:28Z Indexed on 2010/04/07 23:03 UTC
Read the original article Hit count: 1569

Hi,

This was working in MVC 1, but has broken in MVC 2. I'm mocking the HttpContext so I can test routes. The code was originally taken from Steven Sanderson's book. I've tried mocking some extra properties as suggested in this comment but it hasn't fixed it. What am I missing?

This is the start of my test code. routeData is null when this code completes.

// Arange
RouteCollection routeConfig = new RouteCollection();
MvcApplication.RegisterRoutes(routeConfig);
var mockHttpContext = makeMockHttpContext(url);

// Act
RouteData routeData = routeConfig.GetRouteData(mockHttpContext.Object);

This method creates my mock HttpContext:

private static Mock<HttpContextBase> makeMockHttpContext(String url)
{
    var mockHttpContext = new Mock<System.Web.HttpContextBase>();

    // Mock the request
    var mockRequest = new Mock<HttpRequestBase>();
    mockHttpContext.Setup(t => t.Request).Returns(mockRequest.Object);
    mockRequest.Setup(t => t.AppRelativeCurrentExecutionFilePath).Returns(url);

    // Tried adding these to fix in MVC2 (didn't work)
    mockRequest.Setup(r => r.HttpMethod).Returns("GET");
    mockRequest.Setup(r => r.Headers).Returns(new NameValueCollection());
    mockRequest.Setup(r => r.Form).Returns(new NameValueCollection());
    mockRequest.Setup(r => r.QueryString).Returns(new NameValueCollection());
    mockRequest.Setup(r => r.Files).Returns(new Mock<HttpFileCollectionBase>().Object);

    // Mock the response
    var mockResponse = new Mock<HttpResponseBase>();
    mockHttpContext.Setup(t => t.Response).Returns(mockResponse.Object);
    mockResponse.Setup(t => t.ApplyAppPathModifier(It.IsAny<String>())).Returns<String>(t => t);

    return mockHttpContext;
}

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc-2