8

I've spent already half day on this without any success. How do you unit test routes in Web API?

I mean given the following URI:

~/Test/Get/2

I want to unit test that the above url is captured by the Test controller and Get action accepting an int parameter.

svick
  • 236,525
  • 50
  • 385
  • 514
GigaPr
  • 5,206
  • 15
  • 60
  • 77
  • Might be useful? http://stackoverflow.com/questions/10446174/httpclient-with-asp-net-webapi-in-unit-testing-scenario – Jason Evans Jul 08 '12 at 19:53
  • and this: http://www.peterprovost.org/blog/2012/06/16/unit-testing-asp-dot-net-web-api/ – Jason Evans Jul 08 '12 at 19:54
  • You can try to use the NuGet package MvcRouteUnitTester (works pretty easy) http://nuget.org/packages/MvcRouteUnitTester – Styxxy Jul 08 '12 at 21:09

3 Answers3

4

For testing the routes, I have created a library to help you with the assertions - MyWebApi: https://github.com/ivaylokenov/MyWebApi

Basically, you can do the following:

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”
    }));

If you want to implement it yourself, you can see the code here and copy it: https://github.com/ivaylokenov/MyWebApi/blob/master/src/MyWebApi/Utilities/RouteResolvers/InternalRouteResolver.cs

1

I described a ready-to-use example of how to test Web API routes in the related question: Testing route configuration in ASP.NET WebApi

Community
  • 1
  • 1
whyleee
  • 4,019
  • 1
  • 31
  • 33
0

This is what i did, please let me know what you think

[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"]);
}
ahsteele
  • 26,243
  • 28
  • 134
  • 248
GigaPr
  • 5,206
  • 15
  • 60
  • 77
  • Could you please post your mock code for `_httpContexMock` and `_routes`? I've been working on the same issue and asked this question: http://stackoverflow.com/q/11851558/61654. – ahsteele Aug 09 '12 at 02:05