我正在使用 Watin 为使用 T4MVC 的 Asp.Net MVC 应用程序编写规范流测试。
我发现自己在测试中使用“魔术字符串”网址,这是我不喜欢的。
[Given(@"I am on the sign up page")]
public void GivenIAmOnTheSignUpPage()
{
string rootUrl = ConfigurationManager.AppSettings["RootUrl"];
string fullUrl = string.Format("{0}/Authentication/Signup",rootUrl);
WebBrowser.Current.GoTo(fullUrl);
}
我更愿意像在 MVC 应用程序中那样使用我的 T4MVC 操作结果,就像这样......
[Given(@"I am on the sign up page")]
public void GivenIAmOnTheSignUpPage()
{
WebBrowser.Current.GoTo(MVC.Authentication.SignUp().ToAbsoluteUrl());
}
我的ToAbsoluteUrl
扩展方法
public static class RouteHelper
{
private static UrlHelper _urlHelper;
private static string _rootUrl;
public static string ToAbsoluteUrl(this ActionResult result)
{
EnsureUrlHelperInitialized();
var relativeUrl = _urlHelper.Action(result);
return string.Format("{0}/{1}", _rootUrl, relativeUrl);
}
private static void EnsureUrlHelperInitialized()
{
if (_urlHelper==null)
{
_rootUrl = ConfigurationManager.AppSettings["RootUrl"];
var request = new HttpRequest("/", _rootUrl, "");
var response = new HttpResponse(new StringWriter());
var context = new HttpContext(request,response);
HttpContext.Current = context;
var httpContextBase = new HttpContextWrapper(context);
RouteTable.Routes.Clear();
MvcApplication.RegisterRoutes(RouteTable.Routes);
var requestContext = new RequestContext(httpContextBase, RouteTable.Routes.GetRouteData(httpContextBase));
_urlHelper = new UrlHelper(requestContext, RouteTable.Routes);
}
}
}
初始化 RequestContext 和 RouteCollection 以便生成测试 URL 的正确方法是什么?
目前我收到一个 NullReferenceException 就行了var requestContext = new RequestContext(httpContextBase, RouteTable.Routes.GetRouteData(httpContextBase));
。这是新建 requestContext 的正确方法吗?
或者,如果有更好的方法来获取 ActionResult(来自 T4MVC)并将其解析为绝对 url,在 web 应用程序之外,这就是我正在寻找的。