如何测试 UrlHelper.RouteUrl()?

发布于 2024-09-02 11:15:57 字数 725 浏览 6 评论 0原文

我很难弄清楚我需要在测试中模拟什么以表明 UrlHelper.RouteUrl() 返回正确的 URL。它有效,但我希望有正确的测试覆盖率。控制器方法的主要内容如下所示:

var urlHelper = new UrlHelper(ControllerContext.RequestContext);
return Json(new BasicJsonMessage { Result = true, 
   Redirect = urlHelper.RouteUrl(new { controller = "TheController", 
   action = "TheAction", 
   id = somerecordnumber }) });

测试结果对象非常简单,如下所示:

var controller = new MyController();
var result = controller.DoTheNewHotness());
Assert.IsInstanceOf<JsonResult>(result);
var data = (BasicJsonMessage)result.Data;
Assert.IsTrue(data.Result);

result.Redirect 始终为 null,因为控制器显然不知道有关路由的任何信息。我必须对控制器做什么才能让它知道?正如我所说,我知道当我执行生产代码时它是有效的,但我想要一些测试保证。感谢您的帮助!

I'm having a tough go trying to figure out what I need to mock in my tests to show that UrlHelper.RouteUrl() is returning the right URL. It works, but I'd like to have the right test coverage. The meat of the controller method looks like this:

var urlHelper = new UrlHelper(ControllerContext.RequestContext);
return Json(new BasicJsonMessage { Result = true, 
   Redirect = urlHelper.RouteUrl(new { controller = "TheController", 
   action = "TheAction", 
   id = somerecordnumber }) });

Testing the result object is easy enough, like this:

var controller = new MyController();
var result = controller.DoTheNewHotness());
Assert.IsInstanceOf<JsonResult>(result);
var data = (BasicJsonMessage)result.Data;
Assert.IsTrue(data.Result);

result.Redirect is always null because the controller obviously doesn't know anything about the routing. What do I have to do to the controller to let it know? As I said, I know it works when I exercise the production code, but I'd like some testing assurance. Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

从此见与不见 2024-09-09 11:15:57

在我看来,您似乎正在尝试测试自己的一些调用 UrlHelper 的代码,而不是测试框架的 UrlHelper 本身的功能。如果是这种情况,这个答案 ASP.NET MVC: Unit使用 UrlHelper 测试控制器对我来说效果很好。

It sounds to me like you're trying to test some of your own code that invokes a UrlHelper rather than testing the functionality of the framework's UrlHelper itself. If that is the case, this answer ASP.NET MVC: Unit testing controllers that use UrlHelper has worked great for me.

独孤求败 2024-09-09 11:15:57

UrlHelper.RouteUrl() 不是一个框架方法吗?这是 .NET 团队的测试责任,而不是您的!

您可能想要做的是对您的路由配置进行单元测试。 这个问题真的很老了( MVC Beta 1),但答案可能仍然有效。还有 Phil Haack路由调试器 始终为您服务。如果这还不够,谷歌还有很多其他选择。

Isn't UrlHelper.RouteUrl() a framework method? That's the .NET team's responsibility to test, not yours!

What you might want to do is to unit test your route configuration. This question is really old (MVC Beta 1), but the answer might still be valid. And Phil Haack's Routing Debugger is always there for you. If that's not enough, there are tons of other options on Google.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文