简体   繁体   中英

What all unit test cases should I write for following function ? Also, how to provide sample JSONobject as parameter in the function?

Here is the function that I want to unit test. I am writing this in android and since JSONObject is an android class, I can't initiate, I can just mock, But I also want to test for the case where there is sample JSON and it provides correct result or exception (if incorrect sample 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;
    }

Your test cases can be: 1. Test with a single item JSON, assert that the object has the same properties 2. Multiple item JSON, check properties of the objects 3. Test without "items" and see that your method throws an Exception 4. Fool around with individual keys of the Object. I notice that you're not using similar has"key" checks for the Object. This is one area where Unit Testing actually can expose a bug in your code.

Edit: You can build JSONObject via the constructor and add Objects to it, just like a Map. Look it up.

I wouldn't recommend writing this code. Plenty of parsers out there (Gson, Moshi, Jackson) which do this for free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM