How to Mock a Static Singleton?

后端 未结 7 714
伪装坚强ぢ
伪装坚强ぢ 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:19

    Example from Book: Working Effectively with Legacy Code

    To run code containing singletons in a test harness, we have to relax the singleton property. Here’s how we do it. The first step is to add a new static method to the singleton class. The method allows us to replace the static instance in the singleton. We’ll call it setTestingInstance.

    public class PermitRepository
    {
        private static PermitRepository instance = null;
        private PermitRepository() {}
        public static void setTestingInstance(PermitRepository newInstance)
        {
            instance = newInstance;
        }
        public static PermitRepository getInstance()
        {
            if (instance == null) 
            {
                instance = new PermitRepository();
            }
            return instance;
        }
        public Permit findAssociatedPermit(PermitNotice notice) 
        {
        ...
        }
    ...
    }
    

    Now that we have that setter, we can create a testing instance of a PermitRepository and set it. We’d like to write code like this in our test setup:

    public void setUp() {
    PermitRepository repository = new PermitRepository();
    ...
    // add permits to the repository here
    ...
    PermitRepository.setTestingInstance(repository);
    }
    

提交回复
热议问题