Mock static property with moq

前端 未结 6 1921
我在风中等你
我在风中等你 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:12

    You cannot Moq static methods with Moq.

    This is not a bad thing in reality, static methods and classes do have their place but for logic they make unit testing difficult. Naturally you'll run into them when using other libraries. To get around this you'll need to write an adapter (wrapper) around the static code, and provide an interface. For example:

    // Your static class - hard to mock
    class StaticClass
    {
       public static int ReturnOne() 
       {
           return 1;
       }
    }
    
    // Interface that you'll use for a wrapper
    interface IStatic
    {
        int ReturnOne();
    }
    

    Note, I've ommited the concrete class that uses IStatic for the production code. All it would be is a class which uses IStatic and your production code would make use of this class, rather than StaticClass above.

    Then with Moq:

    var staticMock = new Mock();
    staticMock.Setup(s => s.ReturnOne()).Returns(2);
    

提交回复
热议问题