c# – ASP.NET MVC控制器單元測試 – UrlHelper擴充套件的問題
嘗試在我的ASP.NET MVC 3 Web應用程式中進行一些控制器單元測試.
我的測試是這樣的:
[TestMethod] public void Ensure_CreateReviewHttpPostAction_RedirectsAppropriately() { // Arrange. var newReview = CreateMockReview(); // Act. var result = _controller.Create(newReview) as RedirectResult; // Assert. Assert.IsNotNull(result, "RedirectResult was not returned"); }
很簡單基本上測試一個[HttpPost]動作以確保它返回一個RedirectResult(PRG模式).我沒有使用RedirectToRouteResult,因為沒有一個過載支援錨鏈接.繼續.
現在,我使用Moq來模擬Http上下文,包括伺服器變數,控制器上下文,會話等.一切進展順利.
直到我在我的動作方法中擊中了這一行:
return Redirect(Url.LandingPageWithAnchor(someObject.Uri, review.Uri);
LandingPageWithAnchor是一個自定義HTML助手:
public static string LandingPageWithAnchor(this UrlHelper helper, string uri1, string uri2) { const string urlFormat = "{0}#{1}"; return string.Format(urlFormat, helper.RouteUrl("Landing_Page", new { uri = uri1}), uri2); }
基本上,我重定向到另一個頁面,這是一個新的內容的“著陸頁”,新的評論有一個錨點.涼.
現在,由於UrlHelper為null,此方法失敗.
所以我在嘲笑中做到了這一點:
controller.Url = new UrlHelper(fakeRequestContext);
哪個更進一步,但現在它失敗了,因為路由表不包含“Landing_Page”的定義.
所以我知道我需要模擬“什麼”,但不知道是否是:
a)路線表
b)UrlHelper.RouteUrl方法
c)我寫的UrlHelper.LandingPageWithAnchor擴充套件方法
任何人都可以提供一些指導嗎?
編輯
這個特定的路線是在一個區域,所以我嘗試在我的單元測試中呼叫區域註冊:
AreaRegistration.RegisterAllAreas();
但是我得到一個InvalidOperationException:
This method cannot be called during the application’s pre-start initialization stage.
通過嘲笑HttpContext,RequestContext和ControllerContext,註冊路由,然後使用這些路由建立一個UrlHelper來工作.
有點像這樣:
public static void SetFakeControllerContext(this Controller controller, HttpContextBase httpContextBase) { var httpContext = httpContextBase ?? FakeHttpContext().Object; var requestContext = new RequestContext(httpContext, new RouteData()); var controllerContext = new ControllerContext(requestContext, controller); MvcApplication.RegisterRoutes(); controller.ControllerContext = controllerContext; controller.Url = new UrlHelper(requestContext, RouteTable.Routes); }
FakeHttpContext()是一個Moq幫手,它建立所有的模擬東西,伺服器變數,會話等.
http://stackoverflow.com/questions/5943730/asp-net-mvc-controller-unit-testing-problem-with-urlhelper-extension