Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9138065
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T09:12:30+00:00 2026-06-17T09:12:30+00:00

I am trying to do some unit testing of my WebApi route configuration. I

  • 0

I am trying to do some unit testing of my WebApi route configuration. I want to test that the route "/api/super" maps to the Get() method of my SuperController. I’ve setup the below test and am having a few issues.

public void GetTest()
{
    var url = "~/api/super";

    var routeCollection = new HttpRouteCollection();
    routeCollection.MapHttpRoute("DefaultApi", "api/{controller}/");

    var httpConfig = new HttpConfiguration(routeCollection);
    var request = new HttpRequestMessage(HttpMethod.Get, url);

    // exception when url = "/api/super"
    // can get around w/ setting url = "http://localhost/api/super"
    var routeData = httpConfig.Routes.GetRouteData(request);
    request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;

    var controllerSelector = new DefaultHttpControllerSelector(httpConfig);

    var controlleDescriptor = controllerSelector.SelectController(request);

    var controllerContext =
        new HttpControllerContext(httpConfig, routeData, request);
    controllerContext.ControllerDescriptor = controlleDescriptor;

    var selector = new ApiControllerActionSelector();
    var actionDescriptor = selector.SelectAction(controllerContext);

    Assert.AreEqual(typeof(SuperController),
        controlleDescriptor.ControllerType);
    Assert.IsTrue(actionDescriptor.ActionName == "Get");
}

My first issue is that if I don’t specify a fully qualified URL httpConfig.Routes.GetRouteData(request); throws a InvalidOperationException exception with a message of “This operation is not supported for a relative URI.”

I’m obviously missing something with my stubbed configuration. I would prefer to use a relative URI as it does not seem reasonable to use a fully qualified URI for route testing.

My second issue with my configuration above is I am not testing my routes as configured in my RouteConfig but am instead using:

var routeCollection = new HttpRouteCollection();
routeCollection.MapHttpRoute("DefaultApi", "api/{controller}/");

How do I make use of the assigned RouteTable.Routes as configured in a typical Global.asax:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        // other startup stuff

        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        // route configuration
    }
}

Further what I have stubbed out above may not be the best test configuration. If there is a more streamlined approach I am all ears.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T09:12:31+00:00Added an answer on June 17, 2026 at 9:12 am

    I was recently testing my Web API routes, and here is how I did that.

    1. First, I created a helper to move all Web API routing logic there:
        public static class WebApi
        {
            public static RouteInfo RouteRequest(HttpConfiguration config, HttpRequestMessage request)
            {
                // create context
                var controllerContext = new HttpControllerContext(config, Substitute.For<IHttpRouteData>(), request);
    
                // get route data
                var routeData = config.Routes.GetRouteData(request);
                RemoveOptionalRoutingParameters(routeData.Values);
    
                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
                controllerContext.RouteData = routeData;
    
                // get controller type
                var controllerDescriptor = new DefaultHttpControllerSelector(config).SelectController(request);
                controllerContext.ControllerDescriptor = controllerDescriptor;
    
                // get action name
                var actionMapping = new ApiControllerActionSelector().SelectAction(controllerContext);
    
                return new RouteInfo
                {
                    Controller = controllerDescriptor.ControllerType,
                    Action = actionMapping.ActionName
                };
            }
    
            private static void RemoveOptionalRoutingParameters(IDictionary<string, object> routeValues)
            {
                var optionalParams = routeValues
                    .Where(x => x.Value == RouteParameter.Optional)
                    .Select(x => x.Key)
                    .ToList();
    
                foreach (var key in optionalParams)
                {
                    routeValues.Remove(key);
                }
            }
        }
    
        public class RouteInfo
        {
            public Type Controller { get; set; }
    
            public string Action { get; set; }
        }
    
    1. Assuming I have a separate class to register Web API routes (it is created by default in Visual Studio ASP.NET MVC 4 Web Application project, in the App_Start folder):
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    
    1. I can test my routes easily:
        [Test]
        public void GET_api_products_by_id_Should_route_to_ProductsController_Get_method()
        {
            // setups
            var request = new HttpRequestMessage(HttpMethod.Get, "http://myshop.com/api/products/1");
            var config = new HttpConfiguration();
    
            // act
            WebApiConfig.Register(config);
            var route = WebApi.RouteRequest(config, request);
    
            // asserts
            route.Controller.Should().Be<ProductsController>();
            route.Action.Should().Be("Get");
        }
    
        [Test]
        public void GET_api_products_Should_route_to_ProductsController_GetAll_method()
        {
            // setups
            var request = new HttpRequestMessage(HttpMethod.Get, "http://myshop.com/api/products");
            var config = new HttpConfiguration();
    
            // act
            WebApiConfig.Register(config);
            var route = WebApi.RouteRequest(config, request);
    
            // asserts
            route.Controller.Should().Be<ProductsController>();
            route.Action.Should().Be("GetAll");
        }
    
        ....
    

    Some notes below:

    • Yes, I’m using absolute URLs. But I don’t see any issues here, because these are fake URLs, I don’t need to configure anything for them to work, and they representing real requests to our web services.
    • You don’t need to copy you route mappings code to the tests, if they are configured in the separate class with HttpConfiguration dependency (like in the example above).
    • I’m using NUnit, NSubstitute and FluentAssertions in the above example, but of course it’s an easy task to do the same with any other test frameworks.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to learn unit testing. I am trying to unit test some
Im trying to unit test a class in some Java code that I've inherited.
I am new to unit testing and I am trying to test some of
Im using the Prism/Composite Application Library and trying to unit test some code that
I'm trying to do some unit testing on a project that unfortunately has high
I'm trying to unit test some code that calls into VirtualPathUtility.ToAbsolute . Is this
I've been trying to implement unit testing and currently have some code that does
I am trying to implement some unit testing for an old framework. I am
All, I'm trying to do some unit testing in some archaic java code (no
Im trying to write some unit tests for a couple of merthods that are

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.