Mock static property with moq

前端 未结 6 1940
我在风中等你
我在风中等你 2020-11-28 08:37

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

6条回答
  •  青春惊慌失措
    2020-11-28 09:09

    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();
        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

提交回复
热议问题