Power mockito中的TooManyConstructorsFoundException

Dha*_*apu 2 android unit-testing powermock powermockito

我试图模仿JSONArray,并尝试通过抑制构造函数.但是没有一个解决方案适合我.

 JSONArray mockJSONArray=PowerMokcito.mock(JSONArray.class);, 

 whenNew(JSONArray.class).withNoArguments().thenReturn(mockJSONArray);
 whenNew(JSONArray.class).withArguments(anyObject()).thenReturn(mockJSONArray);
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙解决这个问题吗?提前致谢

ksw*_*ghs 11

可以从异常日志本身中识别解决方案.
'请指定参数参数类型'.

异常跟踪:

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 )
Run Code Online (Sandbox Code Playgroud)

下面是当多个构造函数存在时如何使用参数类型的示例.

    @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" } ]
Run Code Online (Sandbox Code Playgroud)