程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> 如何進行ASP.NET MVC的測試

如何進行ASP.NET MVC的測試

編輯:關於ASP.NET

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved