Robotium Automation Test Tutorial for Android

Robotium is a test automation fraemwork for Android, similmar as Selenium for web testing. Basically you use the Robotium library to write Test class that will automate the user action on a device. In this tutorial, you will learn how include Robotium in your Android Studio project and create test class to automate user actions. We will create an Login Activity with username and password EditTexts and a login Button. Then inculde the Robotium test dependency and create a test to automate the action of entering the username and password and hit the login button.

1. Create an Andriod project in Android Studio. Make the Main class name to LoginActivity.java and make sure it is the launcher class.

2. Create a layout file activity_login.xml with the following. If you choose the LoginActivity from the Project creation wizard when creating the project, this file will be already genereated for you, then just replace the content with the following. Why? the goal here is to demonstrate how to use Robotium, better to keep everyting else as simple as possible.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/prompt_email"
        android:inputType="textEmailAddress"
        android:maxLines="1"
        android:singleLine="true" />
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/prompt_password"
        android:imeActionId="@+id/login"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionUnspecified"
        android:inputType="textPassword"
        android:maxLines="1"
        android:singleLine="true" />
    <Button
        android:id="@+id/email_sign_in_button"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/action_sign_in"
        android:textStyle="bold" />
</LinearLayout>

3. Add the following to the LoginActivity.java, if you choose the LoginActivity from the Project creation wizard when creating the project, this file will be already genereated for you, then just replace the content with the following.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {
    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (EditText) findViewById(R.id.email);
        mPasswordView = (EditText) findViewById(R.id.password);

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(), mEmailView.getText().toString() + mPasswordView.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

4. Add robotium as an android test dependency androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.5.3' to the gradle file, so the dependencies in the gradle file looks like the following.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'

    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.5.3'
}

6. Create the Robotium test class, this file should be located in app/src/androidTest/java The same folder as the ApplicationTest class that is auto created for you by Android Studio when you create the project. Let’s create the test class file LoginTest.java with the following code in it.

import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;


@SuppressWarnings("rawtypes")
public class LoginTest extends ActivityInstrumentationTestCase2 {
    private Solo solo;

    private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.example.peng.robotiumunittest.LoginActivity";

    private static Class<?> launcherActivityClass;
    static{
        try {
            launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public LoginTest() throws ClassNotFoundException {
        super(launcherActivityClass);
    }

    public void setUp() throws Exception {
        super.setUp();
        solo = new Solo(getInstrumentation());
        getActivity();
    }

    @Override
    public void tearDown() throws Exception {
        solo.finishOpenedActivities();
        super.tearDown();
    }

    public void testRun() {
        //Wait for activity
        solo.waitForActivity("LoginActivity", 2000);
        //Set default small timeout to 15425 milliseconds
        Timeout.setSmallTimeout(15425);
        //Enter the text: 'test@example.com'
        solo.clearEditText((android.widget.EditText) solo.getView("email"));
        solo.enterText((android.widget.EditText) solo.getView("email"), "test@example.com");
        //Click on Empty Text View
        solo.clickOnView(solo.getView("password"));
        //Enter the text: 'asdfg'
        solo.clearEditText((android.widget.EditText) solo.getView("password"));
        solo.enterText((android.widget.EditText) solo.getView("password"), "asdfg");
        //Click on Sign in or register
        solo.clickOnView(solo.getView("email_sign_in_button"));
    }
}

7. Right click the file LoginTest.java and select run it.

8. To make things even easier, there is the Robotium Recorder which you can use it to record the user actions and it will generated the test class for you. To use the Robotium Recorder, you first have to add it as a plugin in your Android Studio. Go to Preference -> Plugins -> Search for Robotium -> Find it and install it -> restart Android Studio

9. Tools -> Robotium Recorder -> Select an apk or a module -> Next -> New Robotium Test -> It will launch the app on your device or emulator -> do something in your app -> stop -> Save -> You now have the Robotium Test class generated for you. The Recorder will create a new Test module on the same directory level as your app folder. You can now run the test by right click the generated test class and select run.

References:
https://github.com/robotiumtech/robotium
http://robotium.com/pages/installation-android-studio
http://robotium.com/pages/user-guide-android-studio

Search within Codexpedia

Custom Search

Search the entire web

Custom Search