Mocking RouteData to test HtmlHelper RouteLink

Go To StackoverFlow.com

1

The helper:

public static MvcHtmlString RouteLink(this HtmlHelper helper, String linkText, String routeName, Object routeValues, String status)
{
    if (status.ToLower() == "post-game" || status.ToLower() == "mid-game")
    {
        return helper.RouteLink(linkText, routeName, routeValues);
    }

    return MvcHtmlString.Create(" ");
}

The unit test:

[TestMethod]
public void RouteLinkTest()
{
    var httpContext = new Mock<HttpContextBase>();
    var routeData = new Mock<RouteData>();
    var viewContext = new ViewContext { HttpContext = httpContext.Object, RouteData = routeData.Object };

    var helper = new HtmlHelper(viewContext, new Mock<IViewDataContainer>().Object);
    var target01 = helper.RouteLink("Linking Text", "route-name", new { id = "id" }, "status");
    Assert.IsNotNull(target01);
}

The error:

Test method Web.Tests.Extensions.HtmlHelpersTest.RouteLinkTest threw exception: 
System.ArgumentException: A route named 'route-name' could not be found in the route collection.
Parameter name: name

The question: How do I mock the route to have the proper route name?

2012-04-04 21:33
by keeg
I'm guessing a bit, but I would have thought you need to register the route so its in the RouteDictionary - Tim Long 2012-04-05 00:43


0

Instead of mockin the routevalues tell MvcApplication to register them

  var routes = new RouteCollection();
  MvcApplication.RegisterRoutes(routes);

I use it when I have to test some redirectToAction in my controller with something like that

  var controller = GetController();
  var httpContext = Utilities.MockControllerContext(true, false).Object;
  controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);
  var routes = new RouteCollection();
  MvcApplication.RegisterRoutes(routes);
  controller.Url = new UrlHelper(new RequestContext(httpContext, new RouteData()), routes);
  var result = controller.DoMyStuff();
  Assert.IsInstanceOfType(typeof(RedirectResult), result);
  var actual = (RedirectResult)result;
  Assert.AreEqual("/myurl", actual.Url.ToString());

I never tested an helper like yours but I think that should works

2012-04-05 16:38
by Iridio
I've added a route but still same error... var routes = new RouteCollection(); routes.MapRoute( "route-name", "{controller}/{tournament}/{action}/{id}", new { controller = "controller", action = "action", tournament = "", id = "" } ); Application.RegisterRoutes(routes);keeg 2012-04-06 17:50
Ads