4

I have tried to mock JSONArray and also tried by suppressing constructor. But none of the solutions are working for me.

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

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

Can anyone help on this issue ? Thanks in Advance

Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
Sai's Stack
  • 1,345
  • 2
  • 16
  • 29

1 Answers1

15

The solution can be identified from the exception log itself.
'please specify the argument parameter types'.

Exception trace :

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 )

Below is the example how to use parameter types when multiple constructors are there.

    @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" } ]
kswaughs
  • 2,967
  • 1
  • 17
  • 21