Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test route/action resolution of URL with query string?

I'm trying to use code such as the following in my unit tests,

/* Test setup code */
_routes = RouteTable.Routes;
MvcApplication.RegisterRoutes(_routes); //set up the routes as they would be in actual application
/* test code */
Expression<Func<SearchController, ActionResult>> actionFunc;
actionFunc = action => action.Results("x", 3, null);
RouteTestingExtensions.Route(
   "~/Search/Results?searchText=x"
).ShouldMapTo<SearchController>(actionFunc);

The problem is, this is failing with "Expected Results by was Results?searchText=x"

Does anyone have a solution which would allow me to test that a URL (with query string) resolves to the correct controller, action and arguments?

FYI, I don't have an explicit route setup in Global.asax.cs, as the default route works for the actual app - it just doesn't work in this test.

like image 771
Graza Avatar asked May 25 '10 17:05

Graza


1 Answers

IMHO it makes sense to unit test only custom routes. Testing that query string parameters will be translated to controller action arguments is unnecessary and doesn't really bring any value to your application. This work is done by the default model binder and is extensively unit tested by Microsoft (I hope).

This being said MVCContrib.TestHelper allows you to elegantly test custom routes. Suppose for example that you have implemented paging in your application and defined a custom route to have pretty urls for SEO:

routes.MapRoute(
    "Custom",
    "foo/{startPage}/{endPage}",
    new 
    { 
        controller = "Search", 
        action = "Results", 
    }
);

and here's the associated controller:

public class SearchController : Controller
{
    public ActionResult Results(int startPage, int endPage)
    {
        return View();
    }
}

This route could be tested like this:

"~/foo/10/20".ShouldMapTo<SearchController>(c => c.Results(10, 20));

This will effectively test that the default controller is Search, the default action is Results and that both startPage and endPage parameters will be initialized to their respective values from the route.

like image 169
Darin Dimitrov Avatar answered Sep 28 '22 06:09

Darin Dimitrov