嘲笑Asp.net FriendlyUrls

时间:2014-01-29 17:17:37

标签: asp.net unit-testing friendly-url microsoft-fakes

有没有人嘲笑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上下文中运行它时,我的代码工作,我只需要找到一种单元测试它的方法,第一步是模拟shim / stub这个request.GetFriendlyUrlSegments()调用。

1 个答案:

答案 0 :(得分:0)

根据slaks建议,这里伪造的正确数据是Request.RequestContext.RouteData。它需要一个带有&#34; FriendlyUrlSegments&#34;的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.");