How to mock application path when unit testing Web App

Viewed 11281

I am testing code in a MVC HTML helper that throws an error when trying to get the application path:

//appropriate code that uses System.IO.Path to get directory that results in:
string path = "~\\Views\\directory\\subdirectory\\fileName.cshtml";
htmlHelper.Partial(path, model, viewData); //exception thrown here

The exception that is thrown is

System.Web.HttpException: The application relative virtual path '~/Views/directory/subdirectory/fileName.cshtml' cannot be made absolute, because the path to the application is not known.

Following the advice of How to resolve issue with image path when testing HtmlHelper?
I have faked (using Moq):

  • Request.Url to return a string
  • Request.RawUrl to return a string
  • Request.ApplicationPath to return a string
  • Request.ServerVariables to return a null NameValueCollection
  • Response.ApplyAppPathModifier(string virtualPath) to return a string

What else is needed to be able to allow this code to run in the context of a unit test run?
Or
What other approach should I be taking to render a Partial view on a dynamically built string?

6 Answers

This happens once you login to the application and you try to add any new url to the http context and trying to create SimpleWorkerRequest.

in my case i have an url to get the documents from remote server and added the url to http context and trying to authenticate the user and create the SimpleWorkerRequest.

Related