如何進行ASP.NET MVC的測試

來源:互聯網
上載者:User

本文參考了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;    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.