Loading

Testing routes

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

posted @ 2010-12-14 14:34  .net's  阅读(406)  评论(0)    收藏  举报