我正在使用Watin編寫使用T4MVC的Asp.Net MVC應用程序的specflow測試。從非web應用程序使用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);
}
我寧願用我的行動T4MVC結果就像我在MVC應用程序做的,這樣的事情...
[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)並將其解析爲絕對網址,而不是網絡應用程序,那真的是我正在尋找的。
你使用什麼單元測試庫與SpecFlow? MsTest,NUnit還是別的? – danludwig
我正在使用xUnit,這很重要嗎? – Brook
不,我想知道,所以我可以自定義我的答案。我不確定[TestClass]和[AssemblyInitialize]的xunit等價物是什麼,但想象一下它不難發現。 – danludwig