Description: In this post I'm gonna show you how we can create a testcase for our network calls using android InstrumentationTestCase I'm gonna use CoutDownLatch simply becausein most of our app we make network call on background thread. CountDownLatch gives as option to run call single threaded.
Note: test case are event driven if methods are not prefixed with test its not gonna execute.
public void testNetworkCall(){}
Step3: Lets create a dummy network call for demo using aquery and countdown latch.
public class NetworkCallTest extends InstrumentationTestCase { @Override public void setUp() throws Exception { super.setUp(); } public void testNetworkCall(){ CountDownLatch countDownLatch = new CountDownLatch(1); new Thread(new NetworkRunnable(countDownLatch)).start(); } private class NetworkRunnable implements Runnable { private CountDownLatch countDownLatch; public NetworkRunnable(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { AQuery aQuery = new AQuery(getInstrumentation().getContext()); aQuery.ajax( "http://jsonplaceholder.typicode.com/posts" , JSONArray.class , new AjaxCallback<JSONArray>(){ @Override public void callback(String url, JSONArray jsonArray, AjaxStatus status) { assertNotNull("response array is null", jsonArray); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.optJSONObject(i); assertNotNull("jsonObject is null", object); String userId = object.optString("userId"); assertTrue("User Id is empty" , !TextUtils.isEmpty(userId)); String id = object.optString("id"); assertTrue("Id is empty" , !TextUtils.isEmpty(id)); String title = object.optString("title"); assertTrue("title is empty" , !TextUtils.isEmpty(title)); String body = object.optString("body"); assertTrue("body is empty" , !TextUtils.isEmpty(body)); } countDownLatch.countDown(); } }); } } }
Step4:Run the test case . Click to know HOW TO RUN TESTCASES ?.