title: How to use JSONObjects in writing local tests using junit mockito
body: <p>I have a function using JSONObject, which I need to test . Here is my code:</p>
  
  <p><strong>This is the code I wanted to test:</strong></p>
  
  <pre><code>public String getJsonData() {
  try {
      InputStream is = mContext.getAssets().open("chartInfo.json");
      int size = is.available();
      byte[] buffer = new byte[size];
      if (is.read(buffer) &gt; 0)
          jsonString = new String(buffer, "UTF-8");
      is.close();
  
  } catch (IOException ex) {
      ex.printStackTrace();
      return null;
  }
  return jsonString;
  }
  
  public String getChartTypeJS() {
  jsonString = getJsonData();
  try {
      JSONObject jsonObject = new JSONObject(jsonString);
      JSONObject javascriptEvent_JsonObject = jsonObject.getJSONObject("javascript_events");
      return javascriptEvent_JsonObject.getString("chartType");
  } catch (JSONException e) {
      e.printStackTrace();
  }
  return "";
  }
  </code></pre>
  
  <p><strong>My testing code:</strong></p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class LoadJsonData_Test {
  
  @Spy
  private LoadJsonData loadJsonData;
  
  @Test
  public void getChartTypeJS_test() {
  
      String jsonStr = "";
      try {
          InputStream is = this.getClass().getClassLoader().getResourceAsStream("chartInfo.json");
          int size = is.available();
          byte[] buffer = new byte[size];
          if (is.read(buffer) &gt; 0)
              jsonStr = new String(buffer, "UTF-8");
          is.close();
  
      } catch (IOException ex) {
          ex.printStackTrace();
      }
      doReturn(jsonStr).when(loadJsonData).getJsonData();
      assertEquals(loadJsonData.getChartTypeJS(), "javascript:setChartSeriesType(%d);");
  
      }
  
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Error thrown:</strong> java.lang.RuntimeException: Method getJSONObject in org.json.JSONObject not mocked. See <a href="http://g.co/androidstudio/not-mocked" rel="nofollow noreferrer">http://g.co/androidstudio/not-mocked</a> for details.</p>
  
  <p>As you can see I am using JSONObjets to get data from json file. How can we test the outcome of the above functions?</p>
  
  <p>Thanks</p>