我試圖在我的MVC應用程序上運行一些測試,但我一直在經歷一個讓它工作的麻煩世界。我會盡量得到正確的一點是:如何嘲笑或僞造HttpApplication/HttpContext進行測試
我使用RhinoMocks嘗試這樣的事:
設置:
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;
這裏的FakeHttpContext()
方法:
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;
}
我真的需要訪問HttpContextBase.Request.AppRelativeCurrentExecutionFilePath
,但它總是以null
的形式返回。 HttpContext.Current.Request.RequestContext
也是如此。
有人可以幫我嗎?可以肯定的是,我現在絕望了。
你不要告訴問題是什麼?你有錯誤(哪一個?)?據我所見,特定的設置'安裝程序(c => c.Request。AppRelativeCurrentExecutionFilePath)'應該可以工作,因爲'Request'是一個'virtual'屬性'AppRelativeCurrentExecutionFilePath'的'virtual'屬性。你說'_mockContext.SetupAllProperties();'的原因是什麼?您還希望設置其他*屬性? –
@JeppeStigNielsen我更新了我現在使用的問題。我仍然無法工作。 – Kehlan