2012-07-08 64 views
8

我已经花了半天时间没有取得任何成功。你如何在Web API中测试路由?单元测试Web API中的自定义路线

我的意思是给出下面的URI:

~/Test/Get/2 

欲单元测试,上述URL由测试控制器捕获和Get动作受理int参数。

+0

可能是有用的? http://stackoverflow.com/questions/10446174/httpclient-with-asp-net-webapi-in-unit-testing-scenario – 2012-07-08 19:53:42

+0

和这个:http://www.peterprovost.org/blog/2012/06/16/unit-testing-asp-dot-net-web-api/ – 2012-07-08 19:54:27

+0

你可以尝试使用NuGet包MvcRouteUnitTester(很简单)http://nuget.org/packages/MvcRouteUnitTester – Styxxy 2012-07-08 21:09:15

回答

0

这是我做什么,请让我知道你在想什么

[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"]); 
} 
+0

你可以发布你的模拟代码'_httpContexMock'和'_routes'?我一直在研究相同的问题,并提出这个问题:http://stackoverflow.com/q/11851558/61654。 – ahsteele 2012-08-09 02:05:57

3

为了测试路线,我创建了一个库,以帮助你的断言 - 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