测试 HtmlHelper 时如何解决图像路径问题?
我在测试 HTML Helper 时遇到了一个问题。基本上,我正在创建一个网格,其中包含大量行、列和不同类型的数据。标题中还有一个图像,通知用户数据按哪一列排序。然而,当我现在编写测试时(太晚了,但迟到总比不做好,对吧?!),我抛出了这个错误:
“应用程序相对虚拟路径 '~/Images/SortingArrowUp.png' 不能 是绝对的,因为路径 该应用程序未知。”
var imgPath = VirtualPathUtility.ToAbsolute("~/Images/SortingArrowUp.png");
我该如何解决这个问题。我可以理解这在测试过程中可能会出现问题,并且图像可能不可用等等,但是正确的方法是什么?
I came across an issue when I was testing my HTML Helper. Basically I'm creating a grid with loads of rows, columns and different types of data in it. In the header there is also a image to notify the user what column the data is sorted by. However, when I'm writing my test now (way too late, but better late than never right?!), I get this error thrown:
"The application relative virtual path
'~/Images/SortingArrowUp.png' cannot
be made absolute, because the path to
the application is not known."
var imgPath = VirtualPathUtility.ToAbsolute("~/Images/SortingArrowUp.png");
How can I solve this. I can understand how this might be an issue during the test, and the image might not be available and all that, but what's the correct way to do this then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正确的方法是调用
UrlHelper.GenerateContentUrl
而不是VirtualPathUtility
。在您的帮助程序代码中,您将执行以下操作:在单元测试时,您必须传递正确模拟的上下文对象。您需要模拟
HttpContext.Request.ApplicationPath
- 返回一些虚拟应用程序路径,HttpContext.Response.ApplyAppPathModifier()
- 不执行任何操作,HttpContext.Request.ServerVariables< /code> - 返回 null,
HttpContext.Request.Path
和HttpContext.Request.RawUrl
- 返回一些有意义的值。The correct way is to call
UrlHelper.GenerateContentUrl
instead ofVirtualPathUtility
. In your helper code you would do something like this:When unit testing you will have to pass in correctly mocked context objects. You need to mock
HttpContext.Request.ApplicationPath
- return some dummy app path,HttpContext.Response.ApplyAppPathModifier()
- do nothing,HttpContext.Request.ServerVariables
- return null,HttpContext.Request.Path
andHttpContext.Request.RawUrl
- return some value that makes sense.您可以只使用这个重载:
这是
UrlHelper.GenerateContentUrl
内部使用的,您只需要模拟ApplicationPath
即可。You can just use this overload:
This is what
UrlHelper.GenerateContentUrl
uses internally, and you only need to mockApplicationPath
.