如何使用 JSONObjects 使用 junit mockito 编写本地测试

Sin*_*dhu 0 java junit android unit-testing mockito

我有一个使用 JSONObject 的函数,我需要测试它。这是我的代码:

这是我想测试的代码:

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 "";
}
Run Code Online (Sandbox Code Playgroud)

我的测试代码:

@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);");

    }

}
Run Code Online (Sandbox Code Playgroud)

抛出错误: java.lang.RuntimeException:org.json.JSONObject 中的方法 getJSONObject 未模拟。有关详细信息,请参阅http://g.co/androidstudio/not-mocked

如您所见,我正在使用 JSONObjets 从 json 文件获取数据。我们如何测试上述函数的结果?

谢谢

Sin*_*dhu 6

将这一行添加到 Android build.gradle解决了该问题:

testCompile "org.json:json:20140107"
Run Code Online (Sandbox Code Playgroud)