33

I'm trying to write some unit tests to ensure that requests made to my Web API are routed to the expected API controller action with the expected arguments.

I've tried to create a test using the HttpServer class, but I get 500 responses from the server and no information to debug the problem.

Is there a way to create a unit tests for the routing of an ASP.NET Web API site?

Ideally, I'd like to create a request using HttpClient and have the server handle the request and pass it through the expected routing process.

5
  • OK, I am confused. You said "I'm trying to write some unit tests to ensure that requests made to my Web API are routed to the expected API controller action with the expected arguments" and "Is there a way to create a unit tests for the routing of an MVC site". Which one? Also, please provide some code. Commented Oct 15, 2012 at 8:32
  • @tugberk does the distinction between MVC and WebAPI matter? The routing configuration is common to both platforms... Commented Oct 15, 2012 at 9:07
  • @MattDavey it absolutely does! Web API routing is not directly tied to System.Web.Routing and the action selectors of both frameworks behave completely differently. It's almost always a good idea to test Web API routing with integration testing (directly or indirectly as I stated in my answer). Commented Oct 15, 2012 at 9:09
  • I removed the mention of MVC for clarity - I am dealing with the Web API framework and it's so different from MVC, the distinction really matters. Additionally, what code would you have liked to see? My decrepit unit tests aren't worth showing. Commented Oct 15, 2012 at 13:23
  • 1
    The WebApiContrib project makes it pretty straightforward to test the mapping from URLs to Actions & Arguments: github.com/WebApiContrib/WebAPIContrib/blob/master/src/… Example: gist.github.com/carolynvs/4471039 Commented Mar 21, 2013 at 23:29

3 Answers 3

27

I have written a blog post about testing routes and doing pretty much what you are asking about:

http://www.strathweb.com/2012/08/testing-routes-in-asp-net-web-api/

Hope it helps.

Additional advantage is that I used reflection to provide action methods - so instead of using routes with strings, you do add them in a strongly typed manner. With this approach, if your action names ever change, the tests won't compile so you will easily be able to spot errors.

Sign up to request clarification or add additional context in comments.

7 Comments

It would be useful if there was some code provided, supplying a link that is no longer active is hardly a useful accepted answer.
Sorry, I clicked the link on multiple computers and my phone and I was not getting a page returned. I have confirmed that I can get there now. Hopefully it answers my question. Thanks.
@FilipW, it appears to me from your article that you have to redefine the routes for your application in your unit tests. Correct me if I'm wrong, but doesn't that entirely miss the point? (since you're not testing the actual routes you're using in your application)
@FilipW Great article - could you maybe post the examples here also? ya know incase you won't be able to keep your own blog post ;)
It's adavisable to bring at least the bare minimum of an external article (a not SO article) just in case the external article dissapears. Could you update your answer with a little bit of info?
|
9

The best way to test your routes for your ASP.NET Web API application is the integration test your endpoints.

Here is simple Integration test sample for your ASP.NET Web API application. This doesn't mainly test your routes but it invisibly tests them. Also, I am using XUnit, Autofac and Moq here.

[Fact, NullCurrentPrincipal]
public async Task 
    Returns_200_And_Role_With_Key() {

    // Arrange
    Guid key1 = Guid.NewGuid(),
         key2 = Guid.NewGuid(),
         key3 = Guid.NewGuid(),
         key4 = Guid.NewGuid();

    var mockMemSrv = ServicesMockHelper
        .GetInitialMembershipService();

    mockMemSrv.Setup(ms => ms.GetRole(
            It.Is<Guid>(k =>
                k == key1 || k == key2 || 
                k == key3 || k == key4
            )
        )
    ).Returns<Guid>(key => new Role { 
        Key = key, Name = "FooBar"
    });

    var config = IntegrationTestHelper
        .GetInitialIntegrationTestConfig(GetInitialServices(mockMemSrv.Object));

    using (var httpServer = new HttpServer(config))
    using (var client = httpServer.ToHttpClient()) {

        var request = HttpRequestMessageHelper
            .ConstructRequest(
                httpMethod: HttpMethod.Get,
                uri: string.Format(
                    "https://localhost/{0}/{1}", 
                    "api/roles", 
                    key2.ToString()),
                mediaType: "application/json",
                username: Constants.ValidAdminUserName,
                password: Constants.ValidAdminPassword);

        // Act
        var response = await client.SendAsync(request);
        var role = await response.Content.ReadAsAsync<RoleDto>();

        // Assert
        Assert.Equal(key2, role.Key);
        Assert.Equal("FooBar", role.Name);
    }
}

There are a few external helpers I use for this test. The one of them is the NullCurrentPrincipalAttribute. As your test will run under your Windows Identity, the Thread.CurrentPrincipal will be set with this identity. So, if you are using some sort of authorization in your application, it is best to get rid of this in the first place:

public class NullCurrentPrincipalAttribute : BeforeAfterTestAttribute {

    public override void Before(MethodInfo methodUnderTest) {

        Thread.CurrentPrincipal = null;
    }
}

Then, I create a mock MembershipService. This is application specific setup. So, this will be changed for your own implementation.

The GetInitialServices creates the Autofac container for me.

private static IContainer GetInitialServices(
    IMembershipService memSrv) {

    var builder = IntegrationTestHelper
        .GetEmptyContainerBuilder();

    builder.Register(c => memSrv)
        .As<IMembershipService>()
        .InstancePerApiRequest();

    return builder.Build();
}

The GetInitialIntegrationTestConfig method is just initializes my configuration.

internal static class IntegrationTestHelper {

    internal static HttpConfiguration GetInitialIntegrationTestConfig() {

        var config = new HttpConfiguration();
        RouteConfig.RegisterRoutes(config.Routes);
        WebAPIConfig.Configure(config);

        return config;
    }

    internal static HttpConfiguration GetInitialIntegrationTestConfig(IContainer container) {

        var config = GetInitialIntegrationTestConfig();
        AutofacWebAPI.Initialize(config, container);

        return config;
    }
}

The RouteConfig.RegisterRoutes method basically registers my routes. I also have a little extension method to create an HttpClient over the HttpServer.

internal static class HttpServerExtensions {

    internal static HttpClient ToHttpClient(
        this HttpServer httpServer) {

        return new HttpClient(httpServer);
    }
}

Finally, I have a static class called HttpRequestMessageHelper which has bunch of static methods to construct a new HttpRequestMessage instance.

internal static class HttpRequestMessageHelper {

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri) {

        return new HttpRequestMessage(httpMethod, uri);
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri, string mediaType) {

        return ConstructRequest(
            httpMethod, 
            uri, 
            new MediaTypeWithQualityHeaderValue(mediaType));
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri,
        IEnumerable<string> mediaTypes) {

        return ConstructRequest(
            httpMethod,
            uri,
            mediaTypes.ToMediaTypeWithQualityHeaderValues());
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri, string mediaType, 
        string username, string password) {

        return ConstructRequest(
            httpMethod, uri, new[] { mediaType }, username, password);
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri, 
        IEnumerable<string> mediaTypes,
        string username, string password) {

        var request = ConstructRequest(httpMethod, uri, mediaTypes);
        request.Headers.Authorization = new AuthenticationHeaderValue(
            "Basic",
            EncodeToBase64(
                string.Format("{0}:{1}", username, password)));

        return request;
    }

    // Private helpers
    private static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri,
        MediaTypeWithQualityHeaderValue mediaType) {

        return ConstructRequest(
            httpMethod, 
            uri, 
            new[] { mediaType });
    }

    private static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri,
        IEnumerable<MediaTypeWithQualityHeaderValue> mediaTypes) {

        var request = ConstructRequest(httpMethod, uri);
        request.Headers.Accept.AddTo(mediaTypes);

        return request;
    }

    private static string EncodeToBase64(string value) {

        byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value);
        return Convert.ToBase64String(toEncodeAsBytes);
    }
}

I am using Basic Authentication in my application. So, this class has some methods which construct an HttpRequestMessege with the Authentication header.

At the end, I do my Act and Assert to verify the things I need. This may be an overkill sample but I think this will give you a great idea.

Here is a great blog post on Integration Testing with HttpServer. Also, here is another great post on Testing routes in ASP.NET Web API.

1 Comment

Informative answer, but why is this better than unit testing your routes?
2

hi when you going to Test your Routes the main objective is test GetRouteData() with this test you ensure that the route system recognize correctly your request and the correct route is select.

[Theory]
[InlineData("http://localhost:5240/foo/route", "GET", false, null, null)]
[InlineData("http://localhost:5240/api/Cars/", "GET", true, "Cars", null)]
[InlineData("http://localhost:5240/api/Cars/123", "GET", true, "Cars", "123")]
public void DefaultRoute_Returns_Correct_RouteData(
     string url, string method, bool shouldfound, string controller, string id)
{
    //Arrange
    var config = new HttpConfiguration();

    WebApiConfig.Register(config);

    var actionSelector = config.Services.GetActionSelector();
    var controllerSelector = config.Services.GetHttpControllerSelector();

    var request = new HttpRequestMessage(new HttpMethod(method), url);
    config.EnsureInitialized();
    //Act
    var routeData = config.Routes.GetRouteData(request);
    //Assert
    // assert
    Assert.Equal(shouldfound, routeData != null);
    if (shouldfound)
    {
        Assert.Equal(controller, routeData.Values["controller"]);
        Assert.Equal(id == null ? (object)RouteParameter.Optional : (object)id, routeData.
        Values["id"]);
    }
}

this is important but is'not enough, even checking that the correct route is selected and the correct route data are extracted does not ensure that the correct controller and action are selected this is a handy method if you not rewrite the default IHttpActionSelector and IHttpControllerSelector services with your own.

 [Theory]
        [InlineData("http://localhost:12345/api/Cars/123", "GET", typeof(CarsController), "GetCars")]
        [InlineData("http://localhost:12345/api/Cars", "GET", typeof(CarsController), "GetCars")]
        public void Ensure_Correct_Controller_and_Action_Selected(string url,string method,
                                                    Type controllerType,string actionName) {
            //Arrange
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);

            var controllerSelector = config.Services.GetHttpControllerSelector();
            var actionSelector = config.Services.GetActionSelector();

            var request = new HttpRequestMessage(new HttpMethod(method),url);

            config.EnsureInitialized();

            var routeData = config.Routes.GetRouteData(request);
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            //Act
            var ctrlDescriptor = controllerSelector.SelectController(request);
            var ctrlContext = new HttpControllerContext(config, routeData, request)
            {
                ControllerDescriptor = ctrlDescriptor
            };
            var actionDescriptor = actionSelector.SelectAction(ctrlContext);
            //Assert
            Assert.NotNull(ctrlDescriptor);
            Assert.Equal(controllerType, ctrlDescriptor.ControllerType);
            Assert.Equal(actionName, actionDescriptor.ActionName);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.