尝试在我的 ASP.NET MVC 3 网络应用程序中进行一些 Controller 单元测试。
我的测试是这样的:
[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
因为没有一个重载支持 anchor 链接。继续前进。
现在,我正在使用 Moq 模拟 Http 上下文,包括服务器变量、 Controller 上下文、 session 等。到目前为止一切顺利。
直到我在我的操作方法中点击了这一行:
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);
}
基本上,我重定向到另一个页面,该页面是新内容的“着陆页”,带有新评论的 anchor 。很酷。
现在,这个方法之前失败了,因为 UrlHelper
为 null。
所以我在 mock 中这样做了:
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 助手,它创建所有模拟内容、服务器变量、 session 等。
关于c# - ASP.NET MVC Controller 单元测试 - UrlHelper 扩展问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5943730/