模拟静态实例
Mock Static Instance
class Continents{
Map<String,String> COUNTRY_CURRENCY_MAP = Singleton.getInstance().getCountryCurrencyMap()
}
我正在尝试使用 power mockito 模拟 Singleton class,但我做不到。
Continents continents = mock(Continents.class);
PowerMockito.mockStatic(Continents.class);
when(Continents.getInstance()).thenReturn(continents);
when(continents.getCountryCurrencyMap()).thenReturn(new HashMap<String, String>());
但我面临以下问题 -
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)
你添加注释了吗?
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
See this Q&A for related details.
另一种方法是根本不使用 PowerMock:您可以创建一个服务来包装单例并使用普通 Mockito 模拟它。请参阅 the wrapper pattern here.
的一些示例代码
如何在测试中模拟此字段 COUNTRY_CURRENCY_MAP
而不是
Continents continents = mock(Continents.class);
PowerMockito.mockStatic(Continents.class);
when(Continents.getInstance()).thenReturn(continents);
when(continents.getCountryCurrencyMap()).thenReturn(new HashMap<String, String>());
您可以替换为
Continents continents = PowerMockito.spy(new Continents());
HashMap COUNTRY_CURRENCY_MAP = PowerMockito.mock(HashMap.class);
Whitebox.setInternalState(continents, "COUNTRY_CURRENCY_MAP", COUNTRY_CURRENCY_MAP);
class Continents{
Map<String,String> COUNTRY_CURRENCY_MAP = Singleton.getInstance().getCountryCurrencyMap()
}
我正在尝试使用 power mockito 模拟 Singleton class,但我做不到。
Continents continents = mock(Continents.class);
PowerMockito.mockStatic(Continents.class);
when(Continents.getInstance()).thenReturn(continents);
when(continents.getCountryCurrencyMap()).thenReturn(new HashMap<String, String>());
但我面临以下问题 -
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)
你添加注释了吗?
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
See this Q&A for related details.
另一种方法是根本不使用 PowerMock:您可以创建一个服务来包装单例并使用普通 Mockito 模拟它。请参阅 the wrapper pattern here.
的一些示例代码如何在测试中模拟此字段 COUNTRY_CURRENCY_MAP
而不是
Continents continents = mock(Continents.class);
PowerMockito.mockStatic(Continents.class);
when(Continents.getInstance()).thenReturn(continents);
when(continents.getCountryCurrencyMap()).thenReturn(new HashMap<String, String>());
您可以替换为
Continents continents = PowerMockito.spy(new Continents());
HashMap COUNTRY_CURRENCY_MAP = PowerMockito.mock(HashMap.class);
Whitebox.setInternalState(continents, "COUNTRY_CURRENCY_MAP", COUNTRY_CURRENCY_MAP);