C# ASP.net MVC单元测试中的模拟路由约束

C# ASP.net MVC单元测试中的模拟路由约束,c#,unit-testing,asp.net-mvc-4,asp.net-mvc-routing,moq,C#,Unit Testing,Asp.net Mvc 4,Asp.net Mvc Routing,Moq,我正在尝试使用Moq测试带有约束的路线。我不是在测试约束,而是在测试路由,我只想在路由作为路由测试的一部分进行测试时返回true。下面的代码试图模拟测试中的约束,将其设置为始终返回true Mock<SomeRouteConstraint> routeConstraint = new Mock<SomeRouteConstraint>(); routeConstraint.Setup(tC => tC.Match(It.IsAny<HttpContextBas

我正在尝试使用Moq测试带有约束的路线。我不是在测试约束,而是在测试路由,我只想在路由作为路由测试的一部分进行测试时返回true。下面的代码试图模拟测试中的约束,将其设置为始终返回true

Mock<SomeRouteConstraint> routeConstraint = new Mock<SomeRouteConstraint>();
routeConstraint.Setup(tC => tC.Match(It.IsAny<HttpContextBase>(), It.IsAny<Route>(), It.IsAny<string>(), It.IsAny<RouteValueDictionary>(), It.IsAny<RouteDirection>())).Returns(true);

context.Setup(ctx => ctx.Request.AppRelativeCurrentExecutionFilePath).Returns("someurl/thatmaps/toavalue");

RouteData routeData = routes.GetRouteData(context.Object);

Assert.IsNotNull(routeData, "Did not find the route");

这里真正的问题实际上是如何使用模拟路由约束而不是实际约束。上下文中是否存在允许Moq覆盖路由约束的内容?

通过创建一个类将约束名称附加到http项集合来解决此问题。然后在我们自己的路由中重写ProcessConstraint方法,并检查集合中要跳过的约束(每个约束都可以设置为true或false)。请记住,我们测试的是路线,而不是约束

    protected override bool ProcessConstraint(System.Web.HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        bool retValue = false;
        string contraintName = constraint.GetType().Name;

        if (httpContext.Items != null && httpContext.Items.Contains(contraintName))
        {
            //Inspect list of constraints to override
            if (httpContext.Items.Contains(constraint.GetType().Name))
                bool.TryParse(httpContext.Items[constraint.GetType().Name].ToString(), out retValue);
        }
        else
        {
            retValue = base.ProcessConstraint(httpContext, constraint, parameterName, DecodeValues(values), routeDirection);
        }

        return retValue;
    }

发布完整的代码。。什么是可变路由?您实际在哪里使用模拟的
routeConstraint
?您需要在某处使用
routeConstraint.Object
;我们可以看到吗?这是问题的关键,我不确定在哪里使用routeConstraint.Object。尚不清楚如何调用流程约束方法。
    protected override bool ProcessConstraint(System.Web.HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        bool retValue = false;
        string contraintName = constraint.GetType().Name;

        if (httpContext.Items != null && httpContext.Items.Contains(contraintName))
        {
            //Inspect list of constraints to override
            if (httpContext.Items.Contains(constraint.GetType().Name))
                bool.TryParse(httpContext.Items[constraint.GetType().Name].ToString(), out retValue);
        }
        else
        {
            retValue = base.ProcessConstraint(httpContext, constraint, parameterName, DecodeValues(values), routeDirection);
        }

        return retValue;
    }