Phil Cooper
Phil Cooper

Reputation: 3123

Unit testing WebApi routes with custom handlers

I'm having a problem testing routes and I think it's due to the route using a custom handler.

This question points to a similar issue, but doesn't quite fix what I'm doing.

I have a RouteConfiguration class that simply houses the route definitions to enable me to pull them in for the application as well as any testing routines:

// the route
ApiRoutes.MapHttpRoute(
    name: "Custom",
    routeTemplate: "api/service/{service}/{method}/{arguments}",
    defaults: new { arguments = RouteParameter.Optional },
    constraints: null,
    handler: new ServiceDispatcher(_httpConfiguration, _controllerHelper)
);

Now when trying to test this using a similar pattern to this way of mocking the route it doesn't find the route (404). The select part looks like this (other code in this article is not shown):

HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/service/foo/bar/foobar");
DefaultHttpControllerSelector controllerSelector = new DefaultHttpControllerSelector(configuration);
HttpControllerDescriptor descriptor = controllerSelector.SelectController(message);

My (educated?) guess is this DefaultHttpControllerSelector but I don't know how or if it can be changed to support what I'm doing.

So, can I make this current routine work using custom handlers or am I barking up the wrong tree?

Upvotes: 1

Views: 461

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142014

When you have a MessageHandler attached to the route, the controller dispatcher is never even called. It doesn't get that far. If you want to test the routes, I would just call

    var routeDate = config.Routes.GetRouteData(request);

Then you can check the route values and test for the service, method and arguments parameters.

Upvotes: 1

Related Questions