1
class Continents{

    Map<String,String> COUNTRY_CURRENCY_MAP = Singleton.getInstance().getCountryCurrencyMap()

}

I am trying to mock Singleton class using power mockito but I am not able to do it.

Continents continents = mock(Continents.class);
PowerMockito.mockStatic(Continents.class);
when(Continents.getInstance()).thenReturn(continents);
        when(continents.getCountryCurrencyMap()).thenReturn(new HashMap<String, String>());

But I am facing the following issue -

java.lang.ExceptionInInitializerError
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at javassist.runtime.Desc.getClassObject(Desc.java:43)
    at javassist.runtime.Desc.getClassType(Desc.java:152)
    at javassist.runtime.Desc.getType(Desc.java:122)
    at javassist.runtime.Desc.getType(Desc.java:78)
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Atul
  • 133
  • 3
  • 12
  • If any of the answers resolved your issue, please accept click the check mark to the left near the up and down arrows to accept. If you are still having trouble I can look further if you edit your question to answer the question I asked in my answer. – John Vandivier Mar 19 '17 at 15:21

2 Answers2

2

Did you include the annotations?

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)

See this Q&A for related details.

Another approach is not to use PowerMock at all: You can create a service which wraps the singleton and mock that with plain Mockito. See some example code for the wrapper pattern here.

Community
  • 1
  • 1
John Vandivier
  • 2,158
  • 1
  • 17
  • 23
0

How about mocking this field COUNTRY_CURRENCY_MAP in your test instead of

Continents continents = mock(Continents.class);
PowerMockito.mockStatic(Continents.class);
when(Continents.getInstance()).thenReturn(continents);
        when(continents.getCountryCurrencyMap()).thenReturn(new HashMap<String, String>());

You may replace with

Continents continents = PowerMockito.spy(new Continents());
HashMap COUNTRY_CURRENCY_MAP = PowerMockito.mock(HashMap.class);
Whitebox.setInternalState(continents, "COUNTRY_CURRENCY_MAP", COUNTRY_CURRENCY_MAP);
Vanguard
  • 1,336
  • 1
  • 15
  • 30