当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Mocking singleton with PowerMockito

问题描述:

in order to test one of the private method I coded, I need to mock a Singleton.

After testing several methods with PowerMockito :

PowerMockito.mockStatic(UtilDatabaseSoldeAutoCdeCommon.class);

Mockito.when(UtilDatabaseSoldeAutoCdeCommon.getInstance()).thenReturn(mockDatabase);

I could never mock this class. Thus I cannot test my methods as in every of them, I access to database.

UtilDatabaseSoldeAutoCdeCommon is defined as such :

public class UtilDatabaseSoldeAutoCdeCommon extends AbstractUtilDatabase {

private static UtilDatabaseSoldeAutoCdeCommon instance;

private UtilDatabaseSoldeAutoCdeCommon() {

super();

}

public static UtilDatabaseSoldeAutoCdeCommon getInstance() {

if(instance == null) {

instance = new UtilDatabaseSoldeAutoCdeCommon();

}

return instance;

}

...

}

I debugged powermockito when it calls getInstance() but everytime consructor is called, it crashes as it tries to load configuration file (which does not exist).

I precise that config file is defined as a constant in absract parent class of UtilDatabaseEnrichissement and used in constructor.

How could I test this part ?

网友答案:

PrepareForTest the singleton class you mock

网友答案:

I think this should work:

    @PrepareForTest({UtilDatabaseSoldeAutoCdeCommon.class})
    public class SomeTest {
        @Mock
        UtilDatabaseSoldeAutoCdeCommon fakeSingletonInstance;   

        @Test
        public void test() {
             Whitebox.setInternalState(UtilDatabaseSoldeAutoCdeCommon.class, "instance", fakeSingletonInstance);
             // Write here your test
        }
    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: