title: How to test for JSONException in JUnit Test?
body: <p>I would like to test for JSONException in the following method but was unable to achieve it. The following is my implementation:</p>
  
  <p>The method <code>formatresponse</code> within <code>methodA</code> has added the key(UtilClass.Object.YEAR) to the JSONObject, therefore, it is not possible that the key is not present as there aren't other methods within the class to remove the key. I have tried mocking using the mockito framework to throw the JSONException but was not successful in throwing the exception using either <code>thenThrow</code> or <code>doThrow</code>.</p>
  
  <pre><code>private JSONObject response;
  
  public ReturnType methodA(JsonObject request, String ipAddr) {
  
        formatResponse(UtilClass.Object.YEAR, new JSONObject());
  
        for (int i = 0; i &lt; computedYear.length; i++) {
  
           try {
                response.getJSONObject(UtilClass.Object.YEAR).put(computedYear[i], new JSONObject()); &lt;== How do I unit test for this line?
           } catch (JSONException e) {
                System.out.println(e.getMessage())
           }
  
  }
  
  private void formatResponse(String key, Object value) {
       try {
           response.put(key, value);
       } catch (JSONException e) {
           e.printStackTrace();
       }
  }
  
  </code></pre>
  
  <p>The following is my junit code:</p>
  
  <pre><code>private String ipAddr = "127.0.0.1";
  
  public void testMethodA() {
  
       ClassA classAInstance = mock(ClassA.class);
       Mockito.doThrow(JSONException.class).when(classAInstance).methodA(request, ipAddr);
  
       classInstance.methodA(request, ipAddr);
  }
  
  </code></pre>
  
  <p>I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!</p>