如何测试 UrlHelper.RouteUrl()?
我很难弄清楚我需要在测试中模拟什么以表明 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,您似乎正在尝试测试自己的一些调用 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.
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.