2014-01-29 88 views
0

有沒有人嘲笑FriendlyUrls單元測試?Mocking Asp.net FriendlyUrls

我正在寫一個測試,需要模擬asp.net的FriendlyUrls。我需要特別嘲笑的是Request.GetFriendlyUrlSegments()。我正在使用MS Fakes。

這是到目前爲止我的測試:

// Arrange 
      var httpContext = TestHelper.StubHtppContext("", "http://localhost/content.aspx/area/controller/action/OtherRouteValue", ""); 
      var httpContextBase = new HttpContextWrapper(httpContext); 

      RouteTable.Routes.MapRoute(
       "RouteName", 
       "Area/{controller}/{action}/{id}/{OtherRoute}", 
       new {action = "Index", id = UrlParameter.Optional, OtherRoute = UrlParameter.Optional}); 

      RouteTable.Routes.EnableFriendlyUrls(); 

      var segments = new List<String> {"Controller", "Action", "Id", "OtherRoute"}; 


      using (ShimsContext.Create()) 
      { 
       ShimHttpContext.CurrentGet =() => httpContext; 

       ShimFriendlyUrl.SegmentsGet =() => segments; 

       // Act 
       RouteData result = MvcUtility.GetRouteValuesFromUrl(); 

       // Assert 
       Assert.IsNotNull(result, "Expected RouteData to be created."); 
      } 

     } 

系統的測試中的相關部分:

public static RouteData GetRouteValuesFromUrl() 
{ 
    var request = System.Web.HttpContext.Current.Request; 
    var segments = request.GetFriendlyUrlSegments(); 
    //Other code 
} 

我希望爲段用我的墊片獲取並返回我的區隔清單。

我的代碼在我的web上下文中運行時工作,我只需要找到一種方法來對它進行單元測試,第一步是嘲笑填充/存根這個request.GetFriendlyUrlSegments()調用。

+2

爲了使您的代碼可測試,你應該使用一個注入'HttpContextBase',而不是'HttpContext.Current'。 – SLaks

+0

@Slaks,這是一個很好的觀點,但是我不清楚這將如何幫助我填充Request.GetFriendlyUrlSegments()的方法調用。你能詳細說明嗎? – twifosp

+1

嗯;進一步看,它不會在這裏幫助,除非'GetFriendlyUrlSegments'擴展方法的實現使用你可以假冒的數據。 (嘗試一個反編譯器?) – SLaks

回答

0

根據slaks建議,這裏僞造的正確數據是Request.RequestContext.RouteData。它需要一個帶有「FriendlyUrlSegments」鍵的DataToken。

校正和測試工作:

var httpContext = TestHelper.StubHtppContext("", "http://localhost/content.aspx/area/controller/action/OtherRouteValue", ""); 
     var httpContextBase = new HttpContextWrapper(httpContext); 

     RouteTable.Routes.MapRoute(
      "RouteName", 
      "Area/{controller}/{action}/{id}/{OtherRoute}", 
      new {action = "Index", id = UrlParameter.Optional, OtherRoute = UrlParameter.Optional}); 

     RouteTable.Routes.EnableFriendlyUrls(); 

     var segments = new List<String> {"Controller", "Action", "Id", "OtherRoute"}; 

     var requestContext = new StubRequestContext(httpContextBase, new RouteData()); 

     var mockedRouteData = new RouteData(); 
     mockedRouteData.DataTokens.Add("FriendlyUrlSegments", segments); 

     requestContext.RouteDataGet =() => mockedRouteData; 

     using (ShimsContext.Create()) 
     { 
      ShimHttpContext.CurrentGet =() => httpContext; 
      ShimHttpRequest.AllInstances.RequestContextGet = request => requestContext; 

      // Act 
      RouteData result = MvcUtility.GetRouteValuesFromUrl(); 

      // Assert 
      Assert.IsNotNull(result, "Expected RouteData to be created.");