I developed applications for Android, but did not write any unit tests. I recently started to find out about this and tried to use JUnit to test Android applications.
I found that most of the time I get errors in API calls, but I still canβt figure out how to write unit tests for them (and to make the source code testable).
Let me explain the following function:
I run a call to the setOffenceList () function. There are several actions inside a function.
i) Download RestClient and pass the URL.
ii) RestClient talks to the JSON api and gets a response
ii) I grab the response inside the response function onSuccess (String)
iii) Parse JSON data and store it inside an array
iv) If success I show the data in the list view (still show the error message)
This is the code:
public class OffenceFrag extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_offence, container, false); //run API call setOffenceList(); return view; } private void setOffenceList() { String url = Paths.SITE_URL ; RestClient.get(url, null, new AsyncHttpResponseHandler() { @Override public void onStart() { Toast.makeText(getActivity(), "Loading offences...", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(String response) { //Parse JSON JSONArray jsonArray; try { JSONObject jsonObj = new JSONObject(response); if(jsonObj.getString("status").equalsIgnoreCase("Success")){ jsonArray = new JSONArray(jsonObj.getString("data")); if(jsonArray.length() > 0){ for (int i = 0; i < jsonArray.length(); i++) { JSONObject row = jsonArray.getJSONObject(i); OffenceORM off = new OffenceORM(); off.setOffenceId(row.getString("offence_id")); off.setPhoto(row.getString("photo")); off.setSubmittedBy(row.getString("submitted_by")); offenceList.add(off); } } //Success: Show the list view setOffenceAdapter(); Toast.makeText(getActivity(), "Successfully Loaded", Toast.LENGTH_LONG).show(); } else { //Failed: show error message Toast.makeText(getActivity(), "There are no offences submitted under project", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Log.e("exception", e.getMessage()); } } @Override public void onFailure(Throwable error, String content) { Log.e("failed", error.getMessage()); } @Override public void onFinish() { } }); } }//end
I can't figure out how to write a test function for something like the code above.
Can you show me how to break this code into test fragments and write unit test functions to them?
Thanks a lot!