太多构造函数在 Powermockito 中发现异常
TooManyConstructorsFoundException in Power mockito
我试过模拟 JSONArray,也尝试过抑制构造函数。但是 none 的解决方案对我有用。
JSONArray mockJSONArray=PowerMokcito.mock(JSONArray.class);,
whenNew(JSONArray.class).withNoArguments().thenReturn(mockJSONArray);
whenNew(JSONArray.class).withArguments(anyObject()).thenReturn(mockJSONArray);
任何人都可以帮助解决这个问题吗?提前致谢
解决方案可以从异常日志中找到。
'please specify the argument parameter types'.
异常跟踪:
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" } ]
我试过模拟 JSONArray,也尝试过抑制构造函数。但是 none 的解决方案对我有用。
JSONArray mockJSONArray=PowerMokcito.mock(JSONArray.class);,
whenNew(JSONArray.class).withNoArguments().thenReturn(mockJSONArray);
whenNew(JSONArray.class).withArguments(anyObject()).thenReturn(mockJSONArray);
任何人都可以帮助解决这个问题吗?提前致谢
解决方案可以从异常日志中找到。
'please specify the argument parameter types'.
异常跟踪:
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" } ]