Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to write a test case using Robotium in android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 591
    Comment on it

    Today we are going to learn something about J-Unit testing in android. We will be implementing an automation library known as Robotium, for genreating the test cases for testing the various functionalities in our app. First of all you need to add the jar. file of robotium into our project so that you will be able to call its methods.

    Below you find the link for where you can easily download the required jar.

    https://code.google.com/p/robotium/downloads/detail?name=robotium-solo-5.0.1.jar&can=2&q

    Now let us assume there is demo for showing up a general android activity whoes main function is hit web service a retrive the data from the server and prapogate on the respective fields of the screen.

    package com.pacificcheese;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URI;
    import java.net.URISyntaxException;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    
    public class DemoActivity extends Activity{
    
        TextView testingFlag;
        public static boolean apiStatus = false;
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.demo_layout);
    
            testingFlag = (TextView) this.findViewById(R.id.testingFlag);
            new HitGoogleService().execute("https://maps.googleapis.com/maps/api/geocode/json?address=dehradun"
                    + "&key=AIzaSyCilB7GPux2plzH64BAVbFwqrMpAUMDFu8");
    
        }
    
        private class HitGoogleService extends AsyncTask<String, Void, String>{
    
            ProgressDialog dialog;
    
            @Override
            protected void onPreExecute()
            {
                dialog = new ProgressDialog(DemoActivity.this);
                dialog.setMessage("Please wait");
                dialog.show();
            }
    
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                final DefaultHttpClient client = new DefaultHttpClient();
                HttpGet method = null;
    
                try {
                    method = new HttpGet(new URI(params[0]));
    
                }  catch (URISyntaxException e) {   
                    e.printStackTrace();
                }
    
                HttpResponse res=null;
                try 
                {
                    if(client!=null)
                        res = client.execute(method);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(res!=null)
                {
                    /*HttpEntity entity=res.getEntity();*/
                    InputStream input=null;
                    try {
                        input = res.getEntity().getContent();
                        byte[] data = new byte[256];
                        int len = 0;
                        int size = 0;
                        StringBuffer raw = new StringBuffer();
    
                        while ( -1 != (len = input.read(data)) )
                        {
                            raw.append(new String(data, 0, len));
                            size += len;
                        }
                        input.close();
                        return raw.toString();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                        return "";
                    } catch (IOException e) {
                        e.printStackTrace();
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
    
            @Override
            protected void onPostExecute(String response)
            {
                dialog.dismiss();
                Log.d(DemoActivity.class.getSimpleName(), response);
                try {
                    JSONObject responseJsonObject = new JSONObject(response);
                    if(responseJsonObject.getString("status").equalsIgnoreCase("OK")){
                        testingFlag.setText("loaded");
                        apiStatus = true;
                    }
                    else {
                        apiStatus = false;
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
    
        }
    
    }
    

    The layout of the above activity only contains the a TextView has been taken as flag component which will going to indicate the status of the web service. Now given below is the test class which will going to test our main Demo activity.

    package com.pacificcheese.tester;
    
    import android.test.ActivityInstrumentationTestCase2;
    import android.view.inputmethod.EditorInfo;
    import android.widget.EditText;
    
    import com.pacificcheese.DemoActivity;
    import com.pacificcheese.R;
    import com.pacificcheese.utils.Constants;
    import com.robotium.solo.Condition;
    import com.robotium.solo.Solo;
    
    public class DemoTest extends ActivityInstrumentationTestCase2<DemoActivity>{
    
        private Solo solo;
        public DemoTest() {
            super(DemoActivity.class);
        }
    
        @Override
        public void setUp() throws Exception {
            //setUp() is run before a test case is started. 
            //This is where the solo object is created.
            solo = new Solo(getInstrumentation(), getActivity());
        }
    
        @Override
        public void tearDown() throws Exception {
            //tearDown() is run after a test case has finished. 
            //finishOpenedActivities() will finish all the activities that have been opened during the test execution.
            solo.finishOpenedActivities();
        }
    
        public void testLogin() throws Exception {
    
            testApiIntegration();
        }
    
        private void testApiIntegration() {
            // TODO Auto-generated method stub
            solo.unlockScreen();
            solo.sleep(2000);
    
            solo.assertCurrentActivity("This should be Demo Screen", "DemoActivity");
            solo.sleep(500);
    
            while(true){
                if(solo.waitForCondition(new Condition() {
    
                    @Override
                    public boolean isSatisfied() {
                        if(solo.searchText("loaded")){
                            return true;
                        }
                        return false;
                    }
                }, 100))
                    break;
            }
    
            assertEquals("Integreation Failed :-" ,true, DemoActivity.apiStatus);
        }
    }
    

    If we talk about the test class it is slightly differnt from the android activity,it has no attached UI with it. And in this way we are going to test a functionality using robotium libriray in anroid. Undoubtly you can also you also develop your own logics. Remember one thing to run a test case you have to run a project through J-Unit from choosing provided option from running confugrations.

    I have attached the DemoRobotium.zip file of the source code which is available at the bottom.

    Hope this will help you but if you have any questions regrading the same please feel free to ask, it will be admirable. :)

 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: