Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Testing Web Service response using Junit in Android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.19k
    Comment on it

    Unit Testing plays an important role in software development process, basically this testing is done by Developers as they test smallest piece of codes and test whether it gives accurate output or not.Each unit can be tested separately and can be tested again and again.

    Unit testing or TDD i.e Test Driven Development process follow RED-REFACTOR-GREEN process life cycle that means a developer first writes some test code and runs and if it fails that means it's in RED line so you have to REFACTOR and test your code again until you get GREEN line.

    Testing views like TextView, EditText, Activity state are relatively easy but testing web service response using Junit is little bit complicated in Android so Today i am sharing my project so that you can easily test your web service response.

    Main project contains web service http request and getting response back from server.

    1. Interface with callback method that will in your main activity.

      public interface AsyncTaskCompleteListener<Bean> {
      /**
       * Invoked when the AsyncTask has completed its execution.
       * @param result The resulting object from the AsyncTask.
       */
      public void onTaskComplete(Bean result);}
      
    2. Bean class to hold response string

      public class Bean { 
      public String response;
        }
      
    3. Note that it's better to use a comman asyncTask for your project that ll make your codes better, useful, efficient and easy to use, so i am making a common AsynTack class for my project that will call interface call back method to send response back.

    public class DataFetching  extends AsyncTask{
    
        private Context ctx;
        private ProgressDialog dialog;
        private String line;
        private StringBuilder builder = null;
        private InputStream is = null;
        private int code;
        private JSONObject objContects = null;
        AsyncTaskCompleteListener listener;
        Bean bean;
    
    
        public DataFetching(Context context){
            this.ctx = context;
            listener = (AsyncTaskCompleteListener)ctx;
        }
    
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(ctx);
            dialog.setTitle("Data Fetching");
            dialog.setMessage("Fetching...");
            dialog.show();
    
        }
    
        @Override
        protected Bean doInBackground(String... params) {
    
    
            try {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet("http://api.androidhive.info/contacts/");
                HttpResponse response = client.execute(get);
                code = response.getStatusLine().getStatusCode();
                if(code == 200){
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    builder = new StringBuilder();
                    while ((line = reader.readLine())!= null) {
                        builder.append(line);
                    }
                    try {
                        objContects = new JSONObject(builder.toString());
                        bean = new Bean();
                        bean.response = objContects.toString();
                    }
                    catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
    
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            Log.e("json response", "doInBackGround =" + bean.response);
    
            return bean;
        }
    
        @Override
        protected void onPostExecute(Bean bean) {
            super.onPostExecute(bean);
    
            Log.e("data in onPost", "result = "+bean.response);
    
            listener.onTaskComplete(bean);
    
            dialog.dismiss();
    
        }
    }
    
    1. Main activity class that implements interface
    public class MainActivity extends Activity implements  AsyncTaskCompleteListener{
    
        private TextView tvResult;
        private EditText no1;
        private EditText no2;
        private Button btnAdd;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tvResult = (TextView)findViewById(R.id.tvResult);
            no1 = (EditText)findViewById(R.id.no1);
            no2 = (EditText)findViewById(R.id.no2);
            btnAdd = (Button)findViewById(R.id.btnAdd);
    
            btnAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int n1= Integer.parseInt(no1.getText().toString());
                    int n2= Integer.parseInt(no2.getText().toString());
                    int sum = n1+n2;
    
                    tvResult.setText(""+sum);
    
                    new DataFetching(MainActivity.this).execute();
    
                }
            });
    
        }
    
        @Override
        public void onTaskComplete(Bean result) {
            Log.e("json response in listener callback", "onCreate =" + result.response);
    
        }
    }
    
    1. xml layout file
    <EditText android:hint="Enter no1"
            android:text="5"
            android:id="@+id/no1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <EditText android:hint="Enter no2"
            android:id="@+id/no2"
            android:text="4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnAdd"
            android:text="Add"/>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvResult"/>
    

    Now its time to share my activity test codes here where i am testing addition of two numbers and webservice response.

    1. MainActivityTest Class
    public class MainActivityTest extends ActivityInstrumentationTestCase2{
    
        public MainActivityTest() {
            super(MainActivity.class);
        }
    
    
        private String btnExpectedText = "Add";
        private String btnActualText = "";
    
        private int resultExpectedText;
        private int resultActualText;
    
        private int n1;
        private int n2;
    
        private TextView tvResult;
        private EditText no1;
        private EditText no2;
        private Button btnAdd;
    
        MainActivity activity;
    
    
        @Override
        protected void setUp() throws Exception {
            super.setUp();
            activity = getActivity();
    
            tvResult = (TextView) activity.findViewById(R.id.tvResult);
            no1 = (EditText) activity.findViewById(R.id.no1);
            no2 = (EditText) activity.findViewById(R.id.no2);
            btnAdd = (Button) activity.findViewById(R.id.btnAdd);
    
        }
    
        public void testCase1() {
            assertNotNull(tvResult);
            assertNotNull(no1);
            assertNotNull(no2);
            assertNotNull(btnAdd);
            assertNotNull(activity);
            //   assertEquals(resultExpectedText,resultActualText);
        }
    
        public void testCase2() {
            btnActualText = btnAdd.getText().toString();
    
            assertEquals(btnExpectedText, btnActualText);
    
        }
    
        public void testCase3() {
            // create  a signal to let us know when our task is done.
            final CountDownLatch signal = new CountDownLatch(1);
    
    
            try {
                try {
                    runTestOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btnAdd.performClick();
                            n1 = Integer.parseInt(no1.getText().toString());
                            n2 = Integer.parseInt(no2.getText().toString());
    
                            int sum = n1 + n2;
                            resultExpectedText = sum;
                            resultActualText = Integer.parseInt(tvResult.getText().toString());
                            assertEquals(resultExpectedText, resultActualText);
    
                            new DataFetching(activity){
    
                                @Override
                                protected void onPostExecute(Bean bean) {
                                    super.onPostExecute(bean);
    
                                    Log.e("Testing onPost","getting response or not : "+bean.response);
    
                                    signal.countDown();
                                }
                            }.execute();
    
                        }
                    });
                    signal.await(10, TimeUnit.SECONDS);
                }
                catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    
    }
    

    Hope it ll help you a lot, enjoy testing your web services response.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: