2012-04-04 69 views
1

助手:嘲諷的RouteData測試的HtmlHelper RouteLink

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(" "); 
} 

單元測試:

[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); 
} 

錯誤:

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 

問題: 如何嘲笑路線有正確的路線名稱?

+0

我猜測了一下,但我會想你需要註冊路由,以便它在RouteDictionary中。 – 2012-04-05 00:43:25

回答

0

相反mockin的routevalues的告訴MvcApplication註冊它們

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

我使用它時,我一定要考一些redirectToAction在我的控制器與類似的東西

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()); 

我從來沒有測試的幫手像你的,但我認爲這應該有效

+1

我已經添加了一個路線,但仍然是相同的錯誤... routes.MapRoute( 「route-name」,「{controller}/{tournament}/{action}/{id}」, new {controller =「controller」,action =「action」,tournament =「」, id =「」} ); Application.RegisterRoutes(routes);' – keeg 2012-04-06 17:50:37