0

我正在尝试使用 WebApiContrib.Testing 库设置一些路由测试。我的 get 测试(像这样)工作正常......

    [Test]
    [Category("Auth Api Tests")]
    public void TheAuthControllerAcceptsASingleItemGetRouteWithAHashString()
    {
        "~/auth/sjkfhiuehfkshjksdfh".ShouldMapTo<AuthController>(c => c.Get("sjkfhiuehfkshjksdfh"));
    }

我在后期测试中相当迷失 - 我目前有以下失败并出现 NotImplementedException ......

    [Test]
    [Category("Auth Api Tests")]
    public void TheAuthControllerAcceptsAPost()
    {
        "~/auth".ShouldMapTo<AuthController>(c => c.Post(new AuthenticationCredentialsModel()), "POST");
    }

这是完整性的设置和拆卸...

    [SetUp]
    public void SetUpTest()
    {
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }

    [TearDown]
    public void TearDownTest()
    {
        RouteTable.Routes.Clear();
        GlobalConfiguration.Configuration.Routes.Clear();
    }

我要测试的路由是默认的 POST 路由,它映射到这个方法调用......

    [AllowAnonymous]
    public HttpResponseMessage Post([FromBody] AuthenticationCredentialsModel model)
    { *** Some code here that doesn't really matter *** }

我在这个测试没有参数的标准 GET 路由返回所有项目的测试中也失败了......

    [Test]
    [Category("VersionInfo Api Tests")]
    public void TheVersionInfoControllerAcceptsAMultipleItemGetRouteForAllItems()
    {
        "~/versioninfo".ShouldMapTo<VersionInfoController>(c => c.Get());
    }

哪个正在测试这种方法......

    public HttpResponseMessage Get()
    { *** Some code here that doesn't really matter *** }

我读过的几篇文章都推荐了这个库,但我现在不确定我是否做错了什么,或者它是否非常有限,我最好自己动手。

4

2 回答 2

0

在阅读了Whyleee 关于此处另一个问题的帖子后,我最终通过编写自己的方法解决了这个问题 -在 ASP.NET WebApi 中测试路由配置(WebApiContrib.Testing 似乎对我不起作用)

我将他的帖子与 WebApiContrib.Testing 库中我在语法上喜欢的一些元素合并,以生成以下帮助程序类。

这使我可以编写像这样的真正轻量级的测试......

[Test]
[Category("Auth Api Tests")]
public void TheAuthControllerAcceptsASingleItemGetRouteWithAHashString()
{
    "http://api.siansplan.com/auth/sjkfhiuehfkshjksdfh".ShouldMapTo<AuthController>("Get", "hash");
}

[Test]
[Category("Auth Api Tests")]
public void TheAuthControllerAcceptsAPost()
{
    "http://api.siansplan.com/auth".ShouldMapTo<AuthController>("Post", HttpMethod.Post);
}

助手类看起来像这样......

using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Hosting;
using System.Web.Http.Routing;

namespace SiansPlan.Api.Tests.Helpers
{
    public static class RoutingTestHelper
    {
        /// <summary>
        /// Routes the request.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="request">The request.</param>
        /// <returns>Inbformation about the route.</returns>
        public static RouteInfo RouteRequest(HttpConfiguration config, HttpRequestMessage request)
        {
            // create context
            var controllerContext = new HttpControllerContext(config, new Mock<IHttpRouteData>().Object, request);

            // get route data
            var routeData = config.Routes.GetRouteData(request);
            RemoveOptionalRoutingParameters(routeData.Values);

            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            controllerContext.RouteData = routeData;

            // get controller type
            var controllerDescriptor = new DefaultHttpControllerSelector(config).SelectController(request);
            controllerContext.ControllerDescriptor = controllerDescriptor;

            // get action name
            var actionMapping = new ApiControllerActionSelector().SelectAction(controllerContext);

            var info = new RouteInfo(controllerDescriptor.ControllerType, actionMapping.ActionName);

            foreach (var param in actionMapping.GetParameters())
            {
                info.Parameters.Add(param.ParameterName);
            }

            return info;
        }

        #region | Extensions |

        /// <summary>
        /// Determines that a URL maps to a specified controller.
        /// </summary>
        /// <typeparam name="TController">The type of the controller.</typeparam>
        /// <param name="fullDummyUrl">The full dummy URL.</param>
        /// <param name="action">The action.</param>
        /// <param name="parameterNames">The parameter names.</param>
        /// <returns></returns>
        public static bool ShouldMapTo<TController>(this string fullDummyUrl, string action, params string[] parameterNames)
        {
            return ShouldMapTo<TController>(fullDummyUrl, action, HttpMethod.Get, parameterNames);
        }

        /// <summary>
        /// Determines that a URL maps to a specified controller.
        /// </summary>
        /// <typeparam name="TController">The type of the controller.</typeparam>
        /// <param name="fullDummyUrl">The full dummy URL.</param>
        /// <param name="action">The action.</param>
        /// <param name="httpMethod">The HTTP method.</param>
        /// <param name="parameterNames">The parameter names.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static bool ShouldMapTo<TController>(this string fullDummyUrl, string action, HttpMethod httpMethod, params string[] parameterNames)
        {
            var request = new HttpRequestMessage(httpMethod, fullDummyUrl);
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);

            var route = RouteRequest(config, request);

            var controllerName = typeof(TController).Name;
            if (route.Controller.Name != controllerName)
                throw new Exception(String.Format("The specified route '{0}' does not match the expected controller '{1}'", fullDummyUrl, controllerName));

            if (route.Action.ToLowerInvariant() != action.ToLowerInvariant())
                throw new Exception(String.Format("The specified route '{0}' does not match the expected action '{1}'", fullDummyUrl, action));

            if (parameterNames.Any())
            {
                if (route.Parameters.Count != parameterNames.Count())
                    throw new Exception(
                        String.Format(
                            "The specified route '{0}' does not have the expected number of parameters - expected '{1}' but was '{2}'",
                            fullDummyUrl, parameterNames.Count(), route.Parameters.Count));

                foreach (var param in parameterNames)
                {
                    if (!route.Parameters.Contains(param))
                        throw new Exception(
                            String.Format("The specified route '{0}' does not contain the expected parameter '{1}'",
                                          fullDummyUrl, param));
                }
            }

            return true;
        }

        #endregion

        #region | Private Methods |

        /// <summary>
        /// Removes the optional routing parameters.
        /// </summary>
        /// <param name="routeValues">The route values.</param>
        private static void RemoveOptionalRoutingParameters(IDictionary<string, object> routeValues)
        {
            var optionalParams = routeValues
                .Where(x => x.Value == RouteParameter.Optional)
                .Select(x => x.Key)
                .ToList();

            foreach (var key in optionalParams)
            {
                routeValues.Remove(key);
            }
        }

        #endregion
    }

    /// <summary>
    /// Route information
    /// </summary>
    public class RouteInfo
    {
        #region | Construction |

        /// <summary>
        /// Initializes a new instance of the <see cref="RouteInfo"/> class.
        /// </summary>
        /// <param name="controller">The controller.</param>
        /// <param name="action">The action.</param>
        public RouteInfo(Type controller, string action)
        {
            Controller = controller;
            Action = action;
            Parameters = new List<string>();
        }

        #endregion

        public Type Controller { get; private set; }
        public string Action { get; private set; }
        public List<string> Parameters { get; private set; }
    }
}
于 2013-08-30T11:08:41.507 回答
0

这里似乎有一些令人讨厌的问题 - 通过 WebApiContrib.Testing 库进行调试后,我发现了以下内容......

在用于库自己测试的路由映射代码中,路由映射看起来像这样......

        // GET /api/{resource}
        routes.MapHttpRoute(
            name: "Web API Get All",
            routeTemplate: "api/{controller}",
            defaults: new {action = "Get"},
            constraints: new {httpMethod = new HttpMethodConstraint("GET")}
            );

对于基本相同的路线,我的路线映射看起来像这样......

    config.Routes.MapHttpRoute("DefaultApiGet", "{controller}", 
        new { action = "Get" }, 
        new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });

注意约束构建的不同语法。我的路线映射代码不允许使用字符串。也许这是自编写库以来 WebAPI 版本中发生的变化,我不确定,但似乎我试图用 an 测试的任何路线HttpMethodConstraint都会失败。

我正在继续调查这个;我现在有一个“为什么”,但还没有一个“如何解决”。

更新:WebAPI 路由采用两种形式的约束,其中一种只是一个字符串(更多细节在这里 - http://forums.asp.net/p/1777747/4904556.aspx/1?Re+System+Web+Http +路由+IHttpRouteConstraint+vs+系统+Web+路由+IRouteConstraint)。我尝试更改路由表以查看这是否会产生任何影响,但它没有 - 只是为了让您知道!

于 2013-08-30T08:38:48.767 回答