Exemplo n.º 1
0
        /// <summary>
        /// Builds a basic UrlHelper mock
        /// </summary>
        private Mock<UrlHelper> MockUrlHelper(Type controller, BuildMockRouteFunc routeFunc)
        {
            var routeAttributeType = typeof (RouteAttribute);

            // get the base route from the attributes
            var controllerRoutePrefix = controller.CustomAttributes.FirstOrDefault(attr => attr.AttributeType == typeof (RoutePrefixAttribute));
            var routeBase = controllerRoutePrefix != null ? controllerRoutePrefix.ConstructorArguments[0].Value + "/" : "";
            // get the route from the attributes
            var assembly = Assembly.GetAssembly(controller);
            var routeMethods = assembly.GetTypes() // get all methods with RouteAttribute
                            .SelectMany(type => type.GetMembers())
                            .Union(assembly.GetTypes())
                            .Where(type => Attribute.IsDefined(type, routeAttributeType));
            // build a dictionary from the attributes
            var routeAttributes = routeMethods.SelectMany(meth => meth.CustomAttributes.Where(attr => attr.AttributeType == routeAttributeType))
                                              .Where(attr => attr.NamedArguments != null && attr.NamedArguments.Count > 0);
            // ReSharper disable once AssignNullToNotNullAttribute - previous linq assures it is not null
            var routes = routeAttributes.ToDictionary(attr => (string)attr.NamedArguments.FirstOrDefault(na => na.MemberName == "Name").TypedValue.Value,
                                                      attr => routeBase + attr.ConstructorArguments[0]);

            // mock the UrlHelper
            var urlMock = new Mock<UrlHelper>();
            urlMock.Setup(m => m.Route(It.IsAny<string>(), It.IsAny<Dictionary<string, object>>()))
                // try to replace the id param with the param value
                   .Returns(routeFunc(routes));
            return urlMock;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Standard test init actions
        /// </summary>
        protected void TestInitialize(ControllerBase controller, BuildMockRouteFunc routeFunc)
        {
            // mock the UrlHelper
            var urlMock = this.MockUrlHelper(controller.GetType(), routeFunc);
            controller.Url = urlMock.Object;

            AssertRand.AssertionCounter = 0;
        }