【问题标题】:TooManyConstructorsFoundException in Power mockito在 Powermockito 中发现太多构造函数异常
【发布时间】:2015-12-07 08:14:32
【问题描述】:
我尝试模拟 JSONArray 并尝试通过抑制构造函数。但是没有一个解决方案对我有用。
JSONArray mockJSONArray=PowerMokcito.mock(JSONArray.class);,
whenNew(JSONArray.class).withNoArguments().thenReturn(mockJSONArray);
whenNew(JSONArray.class).withArguments(anyObject()).thenReturn(mockJSONArray);
谁能帮助解决这个问题?提前致谢
【问题讨论】:
标签:
android
unit-testing
powermock
powermockito
【解决方案1】:
可以从异常日志本身确定解决方案。
'请指定实参参数类型'。
异常跟踪:
org.powermock.reflect.exceptions.TooManyConstructorsFoundException:
Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.
Matching constructors in class org.json.JSONArray were:
org.json.JSONArray( java.lang.Object.class )
org.json.JSONArray( java.util.Collection.class )
下面是当有多个构造函数时如何使用参数类型的例子。
@Before
public void setUp() throws Exception {
// Mock JSONArray object with desired value.
JSONArray mockJSONArray=PowerMockito.mock(JSONArray.class);
String mockArrayStr = "[ { \"name\" : \"Tricky solutions\" } ]";
PowerMockito.when(mockJSONArray.getString(0)).thenReturn(mockArrayStr);
// mocking constructor
PowerMockito.whenNew(JSONArray.class).withParameterTypes(String.class)
.withArguments(Matchers.any()).thenReturn(mockJSONArray);
}
@Test
public void testJSONArray() throws Exception {
String str = "[ { \"name\" : \"kswaughs\" } ]";
JSONArray arr = new JSONArray(str);
System.out.println("result is : "+arr.getString(0));
}
Output :
result is : [ { "name" : "Tricky solutions" } ]