How to mock application path when unit testing Web App

As an alternative to mocking built-in .net classes, you can

public interface IPathProvider
{
    string GetAbsolutePath(string path);
}

public class PathProvider : IPathProvider
{
    private readonly HttpServerUtilityBase _server;

    public PathProvider(HttpServerUtilityBase server)
    {
        _server = server;
    }

    public string GetAbsolutePath(string path)
    {
        return _server.MapPath(path);
    }
}

Use the above class to get absolute paths.

And for For unit testing you can mock and inject an implementation of IPathProvider that would work in the unit testing environment.

--UPDATED CODE


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.