单元测试 UrlHelper 扩展方法
我正在尝试创建单元测试以确保我的 UrlHelper 扩展方法有效?有谁知道该怎么做?我正在使用 MVC 1.0 和 MvcContrib。我可以测试路线,但无法测试这样的代码:
public static string MoreFloorplans(this UrlHelper urlHelper, long productID, int pageIndex)
{
return urlHelper.Action<CatalogController>(x => x.GetRelatedProducts(productID, pageIndex));
}
I'm trying to create unit tests to make sure my extension methods for UrlHelper work? Does anyone know how to do this? I'm using MVC 1.0 and MvcContrib. I can test the routes but can't test code like this:
public static string MoreFloorplans(this UrlHelper urlHelper, long productID, int pageIndex)
{
return urlHelper.Action<CatalogController>(x => x.GetRelatedProducts(productID, pageIndex));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我按照 Aaronaught 和 Scott H 的指示进行操作,但还是花了一些功夫。我最终得到了这样的东西。
请注意,您应该测试扩展方法,而不是 UrlHelper 本身,因此在 RequestContext 中设置 RouteData 可能超出范围。
I followed the instructions from Aaronaught and Scott H but it took some goofing around. I ended up with something like this.
Note that you should be testing your extension method, not UrlHelper itself, so setting up the RouteData in the RequestContext is probably out of scope.
为了创建
UrlHelper
,您需要一个RequestContext
。为了创建一个有效的RequestContext
,您需要一个HttpContextBase
和一个RouteData
。第二个,RouteData
,应该很容易构建。HttpContextBase
,您必须进行模拟。为此,我建议您查看 Scott H 的 MvcMockHelpers。其中部分内容有点旧,但我认为对于这个特定的测试来说它已经足够好了 - 您真正需要的是
FakeHttpContext
方法及其依赖项。如果您选择该库,您的代码将类似于:我知道您说您正在尝试使用 MvcContrib
TestHelper
项目,但据我所知,该库都是关于测试的控制器。我不确定它是否真的足够精细来测试较低级别的组件。无论如何,你并不真的需要那里的所有东西;您所需要的只是一个RequestContext
。In order to create a
UrlHelper
, you need aRequestContext
. In order to create a functioningRequestContext
, you need anHttpContextBase
and aRouteData
. The second,RouteData
, should be straightforward to construct. TheHttpContextBase
, you have to mock.For that, I'd suggest you look at Scott H's MvcMockHelpers. Parts of that are a little old, but I think it's good enough for this particular test - all you really need is the
FakeHttpContext
method and its dependencies. If you go pick up that library, your code would look something like:I know you say you're trying to use the MvcContrib
TestHelper
project, but as far as I know, that library is all about testing controllers. I'm not sure if it's really granular enough to test a lower-level component. You don't really need all the stuff in there anyway; all you need is aRequestContext
.