Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 317
GigaPr Avatar asked Jul 08 '12 19:07

GigaPr


2 Answers

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

like image 57
Ивайло Кенов Avatar answered Oct 11 '22 01:10

Ивайло Кенов


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

like image 30
whyleee Avatar answered Oct 11 '22 02:10

whyleee