How to resolve issue with image path when testing HtmlHelper?

≡放荡痞女 提交于 2019-11-29 19:00:15

问题


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?


回答1:


The correct way is to call UrlHelper.GenerateContentUrl instead of VirtualPathUtility. In your helper code you would do something like this:

MvcHtmlString MyHelper(this HtmlHelper helper, ...) {
  // other code
  var imgPath = UrlHelper.GenerateContentUrl("~/Images/SortingArrowUp.png",
                                             helper.ViewContext.HttpContext);
  // other code
}

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 and HttpContext.Request.RawUrl - return some value that makes sense.




回答2:


You can just use this overload:

var imgPath = VirtualPathUtility.ToAbsolute("~/Images/SortingArrowUp.png", 
    context.Request.ApplicationPath);

This is what UrlHelper.GenerateContentUrl uses internally, and you only need to mock ApplicationPath.



来源:https://stackoverflow.com/questions/3425133/how-to-resolve-issue-with-image-path-when-testing-htmlhelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!