I have a function using JSONObject, which I need to test . Here is my code:
This is the code I wanted to test:
public String getJsonData() {
try {
InputStream is = mContext.getAssets().open("chartInfo.json");
int size = is.available();
byte[] buffer = new byte[size];
if (is.read(buffer) > 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 "";
}
My testing 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) > 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);");
}
}
Error thrown: java.lang.RuntimeException: Method getJSONObject in org.json.JSONObject not mocked. See http://g.co/androidstudio/not-mocked for details.
As you can see I am using JSONObjets to get data from json file. How can we test the outcome of the above functions?
Thanks