mercredi 4 mai 2016

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 UtilDatabaseEnrichissement extends AbstractUtilDatabase {

private static UtilDatabaseEnrichissement instance;

private UtilDatabaseEnrichissement() {
    super();
}

public static UtilDatabaseEnrichissement getInstance() {
    if(instance == null) {
        instance = new UtilDatabaseEnrichissement();
    }
    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 ?

Aucun commentaire:

Enregistrer un commentaire