【问题标题】:Unit test Custom Route in Web APIWeb API 中的单元测试自定义路由
【发布时间】:2012-07-08 19:47:20
【问题描述】:

我已经花了半天时间没有任何成功。您如何在 Web API 中对路由进行单元测试?

我的意思是给定以下 URI:

~/Test/Get/2

我想单元测试上面的 url 被 Test 控制器捕获并 Get action 接受一个 int 参数。

【问题讨论】:

标签: c# asp.net-mvc-4 asp.net-web-api


【解决方案1】:

为了测试路由,我创建了一个库来帮助您进行断言 - MyWebApi: https://github.com/ivaylokenov/MyWebApi

基本上,您可以执行以下操作:

MyWebApi
    .Routes()
    .ShouldMap(“api/WebApiController/SomeAction/5”)
    .WithJsonContent(@”{“”SomeInt””: 1, “”SomeString””: “”Test””}”)
    .And()
    .WithHttpMethod(HttpMethod.Post)
    .To(c => c.SomeAction(5, new RequestModel
    {
        SomeInt = 1,
        SomeString = “Test”
    }));

如果想自己实现,可以看这里的代码,复制一下: https://github.com/ivaylokenov/MyWebApi/blob/master/src/MyWebApi/Utilities/RouteResolvers/InternalRouteResolver.cs

【讨论】:

    【解决方案2】:

    我在相关问题中描述了如何测试 Web API 路由的现成示例:Testing route configuration in ASP.NET WebApi

    【讨论】:

      【解决方案3】:

      这就是我所做的,请告诉我你的想法

      [Test]
      public void Should_be_able_to_route_to_gettables_action_in_databaseschemaexplorercontroller()
      {
          const string url = "~/DatabaseSchemaExplorer/Tables/DatabaseType/Provider/DataSource/DatabaseName";
      
          _httpContextMock.Expect(c => c.Request.AppRelativeCurrentExecutionFilePath).Return(url);
      
          var routeData = _routes.GetRouteData(_httpContextMock);
      
          Assert.IsNotNull(routeData, "Should have found the route");
          Assert.AreEqual("DatabaseSchemaExplorer", routeData.Values["Controller"]);
          Assert.AreEqual("Tables", routeData.Values["action"]);
          Assert.AreEqual("DatabaseType", routeData.Values["databaseType"]);
          Assert.AreEqual("Provider", routeData.Values["provider"]);
          Assert.AreEqual("DataSource", routeData.Values["dataSource"]);
          Assert.AreEqual("DatabaseName", routeData.Values["databaseName"]);
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      相关资源
      最近更新 更多