我听从了 Aaronaught 和 Scott H 的指示,但花了一些时间。我最终得到了这样的东西。
public UrlHelper GetUrlHelper(
string fileName = "/",
string url="http://localhost",
string queryString="")
{
// Use routes from actual app
var routeCollection = new RouteCollection();
MvcApplication.RegisterRoutes(routeCollection);
//Make a request context
var request = new HttpRequest(fileName, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var httpContextBase = new HttpContextWrapper(httpContext);
var requestContext = new RequestContext(httpContextBase, new RouteData());
// Make the UrlHelper with empty route data
return new UrlHelper(requestContext, routeCollection);
}
public void MoreFloorplans_ReturnsExpectedUrl()
{
var urlHelper = GetUrlHelper();
var actualResult = urlHelper.MoreFloorPlans(1,2);
Assert.AreEqual("/MoreFloorPlans/1/2", actualResult);
}
请注意,您应该测试您的扩展方法,而不是 UrlHelper 本身,因此在 RequestContext 中设置 RouteData 可能超出范围。