How to resolve issue with image path when testing HtmlHelper?

后端 未结 2 379
灰色年华
灰色年华 2021-01-02 10:55

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 i

相关标签:
2条回答
  • 2021-01-02 11:23

    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.

    0 讨论(0)
  • 2021-01-02 11:30

    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.

    0 讨论(0)
提交回复
热议问题