GigaPr
GigaPr

Reputation: 5386

Unit test Custom Route in Web API

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.

Upvotes: 8

Views: 2376

Answers (3)

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

Upvotes: 4

whyleee
whyleee

Reputation: 4049

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

Upvotes: 1

GigaPr
GigaPr

Reputation: 5386

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

Upvotes: 0

Related Questions