Testing routes

本文通过一个简单的测试案例展示了如何验证ASP.NET MVC中默认路由的正确性。当请求/product/list时,期望控制器名为“product”,操作名为“list”,ID使用默认值。

Let’s start off by demonstrating how to write a test of the Default route included in Global.asax.cs. 
This demonstration assumes that when you create a new project using the ASP.NET MVC Web
Application template, you select an MSTest project.

 

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

There are many tests you can write for this route, but let’s start off with a simple one. When you
make a request for /product/list, you expect that route data for “controller” will have the value
“product” and the route data for “action” will have the value “list”. Because you did not sup-
ply a value for “id” in your URL, you expect that the route data value for “id” will use the default
value of an UrlParameter.Optional.

/// <summary>
        ///A test for RegisterRoutes
        ///</summary>
        [TestMethod()]
        public void RegisterRoutesTest()
        {
            //arrange
            RouteCollection routes = new RouteCollection();
            MvcApplication.RegisterRoutes(routes);
            var httpContextMock = new Mock<HttpContextBase>();
            httpContextMock.Setup(c => c.Request
              .AppRelativeCurrentExecutionFilePath).Returns("~/product/list");
            //act
            RouteData routeData = routes.GetRouteData(httpContextMock.Object);

            //assert
            Assert.IsNotNull(routeData, "Should have found the route");
            Assert.AreEqual("product", routeData.Values["Controller"]);
            Assert.AreEqual("list", routeData.Values["action"]);
            Assert.AreEqual(UrlParameter.Optional, routeData.Values["id"]);
        }

professional asp.net mvc 2

转载于:https://www.cnblogs.com/joe-yang/archive/2010/12/14/1905525.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值