Singleton and unit testing

前端 未结 12 1743
一生所求
一生所求 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 11:05

    Use PowerMock to mock Singleton class (SingletonClassHelper) instance and non-static method (nonStaticMethod) which is called in task.execute().

        import static org.mockito.Mockito.when;
    
        import org.junit.Before;
        import org.junit.Test;
        import org.junit.runner.RunWith;
        import org.mockito.InjectMocks;
        import org.mockito.Mock;
        import org.mockito.Mockito;
        import org.powermock.api.mockito.PowerMockito;
        import org.powermock.core.classloader.annotations.PrepareForTest;
        import org.powermock.modules.junit4.PowerMockRunner;
    
        @PrepareForTest({ SingletonClassHelper.class })
        @RunWith(PowerMockRunner.class)
        public class ClassToTest {
    
            @InjectMocks
            Task task;
    
            private static final String TEST_PAYLOAD = "data";
            private SingletonClassHelper singletonClassHelper;
    
    
            @Before
            public void setUp() {
                PowerMockito.mockStatic(SingletonClassHelper.class);
                singletonClassHelper = Mockito.mock(SingletonClassHelper.class);
                when(SingletonClassHelper.getInstance()).thenReturn(singletonClassHelper);
            }
    
            @Test
            public void test() {
                when(singletonClassHelper.nonStaticMethod(parameterA, parameterB, ...)).thenReturn(TEST_PAYLOAD);
                task.execute();
            }
        }
    

提交回复
热议问题