3

我试图模拟 JSONArray 并尝试通过抑制构造函数。但是没有一个解决方案对我有用。

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

 whenNew(JSONArray.class).withNoArguments().thenReturn(mockJSONArray);
 whenNew(JSONArray.class).withArguments(anyObject()).thenReturn(mockJSONArray);

任何人都可以帮助解决这个问题吗?提前致谢

4

1 回答 1

14

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

异常跟踪:

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" } ]
于 2015-09-11T07:25:18.810 回答