本文參考了http://stephenwalther.com/blog/的內容。
今天需要對ASP.NET MVC的Controller進行測試,我們都知道當我們在測試工程裡new一個controller時,這個controller裡的httpcontext是空的,也就是session,cookie, form等都是空。
方法一:Mock controller的HttpContext, 暫時失敗
那麼我們如何對controller進行測試呢,我首先想到的是mock一個httpcontext,這裡我用的是Rhino Mocks
public static class MvcMockHelpers { public static HttpContextBase FakeHttpContext(this MockRepository mocks) { 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.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; } public static HttpContextBase FakeHttpContext(this MockRepository mocks, string url) { HttpContextBase context = FakeHttpContext(mocks); context.Request.SetupRequestUrl(url); return context; } public static void SetFakeControllerContext(this MockRepository mocks, Controller controller) { var httpContext = mocks.FakeHttpContext(); ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller); controller.ControllerContext = context; }