开发者

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

开发者 https://www.devze.com 2022-12-31 08:30 出处:网络
I\'m trying to use code such as the following in my unit tests, /* Test setup code */ _routes = RouteTable.Routes;

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消