How to use JSONObjects in writing local tests usin

2019-09-20 14:43发布

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

2条回答
Melony?
2楼-- · 2019-09-20 15:14

To make the method easier to test you could pass jsonString as a parameter:

public String getChartTypeJS(String jsonString) {
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject javascriptEvent_JsonObject = jsonObject.getJSONObject("javascript_events");
        return javascriptEvent_JsonObject.getString("chartType");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return "";
}

Then in your test you don't need this line:

doReturn(jsonStr).when(loadJsonData).getJsonData();
查看更多
Lonely孤独者°
3楼-- · 2019-09-20 15:37

Adding this line to Android build.gradle solved the issue:

testCompile "org.json:json:20140107"
查看更多
登录 后发表回答