How to Mock a Static Singleton?

后端 未结 7 718
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 23:05

I have number of classes I\'ve been asked to add some unit tests to with Rhino Mocks and having some issues.

First off, I know RhinoMocks doesn\'t allow for the mock

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 23:28

    You can mock the interface, ISomeInterface. Then, refactor the code that uses it to use dependency injection to get the reference to the singleton object. I have come across this problem many times in our code and I like this solution the best.

    for example:

    public class UseTheSingleton
    {
        private ISomeInterface myX;
    
        public UseTheSingleton(ISomeInterface x)
        {
            myX = x;
        }
    
        public void SomeMethod()
        {
            myX.
        }
    }
    

    Then ...

    UseTheSingleton useIt = UseTheSingleton(Example1.Instance);
    

提交回复
热议问题