这里是我要进行单元测试的功能。我在android中编写此代码,由于JSONObject是一个android类,因此无法初始化,只能进行模拟,但是我也想测试是否存在示例JSON并提供正确的结果或异常(如果示例不正确)的情况JSON)
public List<GithubRepositorySchema> parseAndReturnGithubRepositorySearchResponse(JSONObject response) throws Exception {
List<GithubRepositorySchema> githubRepositorySchemas = new ArrayList<>();
if (response.has("items")) {
JSONArray items = response.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
JSONObject repoObj = items.getJSONObject(i);
githubRepositorySchemas.add(new GithubRepositorySchema(
repoObj.getString("name"),
repoObj.getBoolean("private"),
repoObj.getString("description"),
repoObj.getString("language"),
repoObj.getInt("forks_count"),
repoObj.getInt("open_issues"),
repoObj.getInt("watchers")
));
}
} else {
throw new JSONException("Incorrect Json");
}
return githubRepositorySchemas;
}
您的测试用例可以是:1.使用单个项目JSON进行测试,断言该对象具有相同的属性2.多个项目JSON,检查对象的属性3.在没有“ items”的情况下进行测试,并查看您的方法抛出异常4.随意浏览对象的各个键。我注意到您没有使用类似的具有“键”检查对象的对象。这是单元测试实际上可以在代码中暴露错误的地方。
我不建议编写此代码。大量解析器(Gson,Moshi,Jackson)免费提供。]