I am pretty new to use moq. I am into creating some unit test case to HttpModule
and everything works fine until I hit a static
property as follows
this.applicationPath = (HttpRuntime.AppDomainAppVirtualPath.Length > 1) ? HttpRuntime.AppDomainAppVirtualPath : String.Empty;
I do not know how create mocks for static
class and property like HttpRuntime.AppDomainAppVirtualPath
. The context
, request
and response
have been mocked well with sample code I get from moq. I will appreciate if somebody can help me on this.
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