newbie_86
newbie_86

Reputation: 4610

Unit test asp.net route mapping extension method

I have an extension class for Routes. I want to test the updated list of routecollection. This is an extract:

public static void MapMyRoutes(this RouteCollection routes)
{
    //do some stuff
    routes.MapHttpRoute(null, controllerPath.Path, new { @namespace = controllerPath.Namespace, controller = controllerPath.ControllerName, id = UrlParameter.Optional });
}

I want to unit test this extension, but can't work out how to extract the mapped url from the routecollection:

This is a test:

[TestMethod]
public void TestMapMyRoutesMapsCorrectly()
{
    var routes = new RouteCollection();
    routes.MapMyRoutes();

    foreach (var route in routes)
    {
        Assert.AreEqual(route.??, "v1/api/myRoute");
    }
}

Upvotes: 3

Views: 83

Answers (2)

vmasule
vmasule

Reputation: 99

To be honest you are putting wrong logic to test void method. As your method is void you should use mock framework and pass the mocked RouteCollection object in MapMyRoutes(this RouteCollection routes) method and then verify routes.MapHttpRoute method call.

Refer this link for code implementation

Upvotes: 0

stuartd
stuartd

Reputation: 73243

RoutesCollection is defined as a Collection<RouteBase> so cast each item as a Route, ie:

foreach (var route in routes.Cast<Route>())
{
    // Url may not in fact be the correct property …
    Assert.AreEqual(route.Url, "v1/api/myRoute");
}

Upvotes: 1

Related Questions