【发布时间】:2018-01-16 14:03:37
【问题描述】:
我有一个使用 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 "";
}
我的测试代码:
@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);");
}
}
引发错误: java.lang.RuntimeException:org.json.JSONObject 中的 getJSONObject 方法未模拟。详情请见http://g.co/androidstudio/not-mocked。
如您所见,我正在使用 JSONObjets 从 json 文件中获取数据。我们如何测试上述函数的结果?
谢谢
【问题讨论】:
-
你分享完整的 LoadJsonData 类吗?
标签: java android unit-testing junit mockito