Espresso automation test sample code for Android

Espresso is a automation test fraemwork for Android open source by Google,Basically you use the Espresso to write Test class that will automate the user action on a device. In this tutorial, you will learn how to use Espresso in your Android Studio project and create test class to automate user actions. We will create a Main Activity and a Second Activity. The Main Activivity will have an EditText and a Button, when you click the button, it will submit the text from the EditText to the Second Activity. The Second Activity contains only a TextView.

1. Create the layout files for the Main Activity and the Second Activity.
activit_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:andriod="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <EditText
        android:id="@+id/ed_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btn_submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit"/>
</LinearLayout>

activit_second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_msg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:textSize="30dp"
        android:text="MESSAGE"
        />
</LinearLayout>

2. Create the MainAcitivty.java and SecondActivity.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {



    private EditText edText;
    private Button btnSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edText = (EditText) findViewById(R.id.ed_text);
        btnSubmit = (Button) findViewById(R.id.btn_submit);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSecondActivity();
            }
        });
    }

    private void toSecondActivity(){
        Intent i = new Intent(this, SecondActivity.class);
        i.putExtra("msg", edText.getText().toString());
        startActivity(i);
    }
}

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {

    private TextView tvMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        tvMsg = (TextView) findViewById(R.id.tv_msg);
        String msg = getIntent().getStringExtra("msg");
        tvMsg.setText(msg);
    }
}

3. Let’s tell the gradle build file to use AndroidJUnitRunner by adding the following to the defaultConfig attribute so it looks like this

    defaultConfig {
        //Other configs....
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

4. Add the test dependencies for using Espresso to the dependencies attribute in the gradle file so it looks like this.

dependencies {
    // Other dependencies ....
    // Testing-only dependencies
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support:support-annotations:23.1.0'
    androidTestCompile 'com.android.support.test:runner:0.4.1'
    androidTestCompile 'com.android.support.test:rules:0.4.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
}

5. Finally, let’s create the test file SendMessageTest.java in the androidTest package in the app/src/androidTest/java folder. It should be right next to your main package if you are in the Android view perspective in your project tool window (file naviation window on the left). Run this file by right click it and select run.

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import android.app.Activity;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;


/**
 * Basic tests showcasing simple view matchers and actions like {@link ViewMatchers#withId},
 * {@link ViewActions#click} and {@link ViewActions#typeText}.
 * <p>
 * Note that there is no need to tell Espresso that a view is in a different {@link Activity}.
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class SendMessageTest {

    public static final String MESSAGE = "Hello Espresso";


    /**
     * A JUnit {@link Rule @Rule} to launch your activity under test. This is a replacement
     * for {@link ActivityInstrumentationTestCase2}.
     * <p>
     * Rules are interceptors which are executed for each test method and will run before
     * any of your setup code in the {@link Before @Before} method.
     * <p>
     * {@link ActivityTestRule} will create and launch of the activity for you and also expose
     * the activity under test. To get a reference to the activity you can use
     * the {@link ActivityTestRule#getActivity()} method.
     */
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    @Test
    public void testSendMessage() {
        // Enter text and then hit the submit button.
        onView(withId(R.id.ed_text)).perform(typeText(MESSAGE), closeSoftKeyboard());
        onView(withId(R.id.btn_submit)).perform(click());

        // This view is in a different Activity, no need to tell Espresso.
        onView(withId(R.id.tv_msg)).check(matches(withText(MESSAGE)));
    }

}

Complete example in Github
References:
https://github.com/googlesamples/android-testing

Search within Codexpedia

Custom Search

Search the entire web

Custom Search