Singleton and unit testing

前端 未结 12 1524
一生所求
一生所求 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:58

    You could use reflection to reset your singleton object to prevent tests from affecting each other.

    @Before
    public void resetSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
       Field instance = MySingleton.class.getDeclaredField("instance");
       instance.setAccessible(true);
       instance.set(null, null);
    }
    

    Ref: unit-testing-singletons

提交回复
热议问题