Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock application path when unit testing Web App

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?

like image 804
StuperUser Avatar asked Jun 21 '11 15:06

StuperUser


1 Answers

For what it's worth, I ran up against the same error and followed it through the System.Web source to find it occurs because HttpRuntime.AppDomainAppVirtualPathObject is null.

This is an immutable property on the HttpRuntime singleton, initialized as follows:

Thread.GetDomain().GetData(key) as String

where key is ".appVPath". i.e. it comes from the AppDomain. It might be possible to spoof it with:

Thread.GetDomain().SetData(key, myAbsolutePath)

But honestly the approach in the accepted answer sounds much better than mucking around with the AppDomain.

like image 112
Chris Bowdon Avatar answered Oct 06 '22 00:10

Chris Bowdon