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 ?.
When talking about what Android does well, you can’t avoid the comparison with its partner in duopoly – Apple. Let’s analyze how Android is beneficial to developers and where it beats or ties with iOS. Thank you :) Charlotte W. from mobile app development chicago
ReplyDeleteGreat Article
ReplyDeleteandroid based projects
Java Training in Chennai
Project Center in Chennai
Java Training in Chennai
projects for cse
The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai