Mock static property with moq

Moq can’t fake static members.

As a solution you can create a wrapper class (Adapter Pattern) holding the static property and fake its members.
For example:

public class HttpRuntimeWrapper
{
    public virtual string AppDomainAppVirtualPath 
    { 
        get
        { 
            return HttpRuntime.AppDomainAppVirtualPath; 
        }
    }
}

In the production code you can access this class instead of HttpRuntime and fake this property:

[Test]
public void AppDomainAppVirtualPathTest()
{
    var mock = new Moq.Mock<HttpRuntimeWrapper>();
    mock.Setup(fake => fake.AppDomainAppVirtualPath).Returns("FakedPath");

    Assert.AreEqual("FakedPath", mock.Object.AppDomainAppVirtualPath);
}

Another solution is to use Isolation framework (as Typemock Isolator) in which you can fake static classes and members.
For example:

Isolate.WhenCalled(() => HttpRuntime.AppDomainAppVirtualPath)
       .WillReturn("FakedPath");

Disclaimer – I work at Typemock

Leave a Comment