How to mock or fake HttpApplication / HttpContext for testing

Viewed 6655

I'm trying to run some tests on my MVC application but I've been experiencing a world of trouble getting it to work. I'll try to get right to the point:

I'm using RhinoMocks to try something like this:

Setup:

MockRepository mocks = new MockRepository();
HttpContextBase _mockContext = mocks.FakeHttpContext();
mocks.SetFakeControllerContext(new LoginController());
HttpApplicationStateBase appState = MockRepository.GenerateStub<HttpApplicationStateBase>();
_mockContext.Expect(mc => mc.Application).Return(appState);
HttpContext.Current = _mockContext.ApplicationInstance.Context;

Here's the FakeHttpContext() method:

public static HttpContextBase FakeHttpContext(this MockRepository mocks)
{
    HttpApplication app = mocks.PartialMock<HttpApplication>();

    HttpContextBase context = mocks.PartialMock<HttpContextBase>();
    HttpRequestBase request = mocks.PartialMock<HttpRequestBase>();
    HttpResponseBase response = mocks.PartialMock<HttpResponseBase>();
    HttpSessionStateBase session = mocks.PartialMock<HttpSessionStateBase>();
    HttpServerUtilityBase server = mocks.PartialMock<HttpServerUtilityBase>();

    SetupResult.For(context.ApplicationInstance).Return(app);

    SetupResult.For(context.Request).Return(request);
    SetupResult.For(context.Response).Return(response);
    SetupResult.For(context.Session).Return(session);
    SetupResult.For(context.Server).Return(server);

    mocks.Replay(context);
    return context;
}

I really need to access HttpContextBase.Request.AppRelativeCurrentExecutionFilePath but it's always returned as null. The same goes for HttpContext.Current.Request.RequestContext.

Can anybody help me out here? It's safe to say I'm desperate at this point.

2 Answers
Related