using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Routing; namespace UrlsAndRoutes.Tests { [TestClass] public class RouteTests { private HttpContextBase CreateHttpContext(string targetUrl = null, string httpMethod = "GET") { // create the mock request Mock mockRequet = new Mock(); mockRequet.Setup(m => m.AppRelativeCurrentExecutionFilePath).Returns(targetUrl); mockRequet.Setup(m => m.HttpMethod).Returns(httpMethod); // create the mock response Mock mockResponse = new Mock(); mockResponse.Setup(m => m.ApplyAppPathModifier(It.IsAny())).Returns(s => s); // create the mock context, using the request and response Mock mockContext = new Mock(); mockContext.Setup(m => m.Request).Returns(mockRequet.Object); mockContext.Setup(m => m.Response).Returns(mockResponse.Object); // return the mocked context return mockContext.Object; } private void TestRouteMatch( string url, string controller, string action, object routeProperties = null, string httpMethod = "GET") { // Arrange RouteCollection routes = new RouteCollection(); RouteConfig.RegisterRoutes(routes); // Act - process the route RouteData result = routes.GetRouteData(CreateHttpContext(url, httpMethod)); // Assert Assert.IsNotNull(result); Assert.IsTrue(TestIncomingRouteResult(result, controller, action, routeProperties)); } private bool TestIncomingRouteResult( RouteData routeResult, string controller, string action, object propertySet = null) { Func valCompare = (v1, v2) => { return StringComparer.InvariantCultureIgnoreCase.Compare(v1, v2) == 0; }; bool result = valCompare(routeResult.Values["controller"], controller) && valCompare(routeResult.Values["action"], action); if (propertySet != null) { PropertyInfo[] propInfo = propertySet.GetType().GetProperties(); foreach (PropertyInfo pi in propInfo) { if (!(routeResult.Values.ContainsKey(pi.Name) && valCompare(routeResult.Values[pi.Name],pi.GetValue(propertySet, null)))) { result = false; break; } } } return result; } private void TestRouteFail(string url) { // Arrange RouteCollection routes = new RouteCollection(); RouteConfig.RegisterRoutes(routes); // Act - process the route RouteData result = routes.GetRouteData(CreateHttpContext(url)); // Assert Assert.IsTrue(result == null || result.Route == null); } [TestMethod] public void TestIncomingRoutes() { TestRouteMatch("~/", "Home", "Index"); TestRouteMatch("~/Customer", "Customer", "Index"); TestRouteMatch("~/Customer/List", "Customer", "List"); TestRouteFail("~/Customer/List/All"); TestRouteMatch("~/Shop/Index", "Home", "Index"); } } }