Singleton and unit testing

前端 未结 12 1537
一生所求
一生所求 2021-01-30 10:24

The Effective Java has the following statement on unit testing singletons

Making a class a singleton can make it difficult to test its clients, as it’s im

12条回答
  •  死守一世寂寞
    2021-01-30 10:56

    The problem with singletons (and also with static methods) is that it makes it hard to replace the actual code with a mocked implementation.

    For example consider the following code

    public class TestMe() {
      public String foo(String data) {
        boolean isFeatureFlag = MySingletonConfig.getInstance().getFeatureFlag();
        if (isFeatureFlag)
          // do somethine with data
        else
          // do something else with the data
         return result;
      }
    }
    

    It is not easy to write a unit test for the foo method and verifying the correct behavior is performed. This is because you can't easily change the return value of getFeatureFlag.

    The same problem exists for static methods - it's not easy to replace the actual target class method with a mock behavior.

    Sure, there are workarounds like powermock, or dependency injection to the method, or reflection in tests. But it is much better not to use singletons in the first place

提交回复
热议问题