Android SDK interface testing

Recent exposure to the first Android project, is the interface test on Android. So called a pass to find information, read all kinds of articles, documents, but not very suitable.

Now I decide to write down the learning process, if can help to one or two as in the case of my very happy, learned to record the learning notes.

 Android provides a series of powerful testing tools, the Android environment, extend the JUnit testing framework. The application allows you to more complex test, including the unit level and frame level.

Android test tool consists of several packages: android.test, android.test.mock, android.test.suitebuilder, the most important of the package is android.test.

We see android.test package class relations:

We can see this inside the class divided into two system,  

AndroidTestCase system

Inherited from the JUnit TestCase, you cannot use the Instrumentation framework. But these classes include access to system objects (such as Context) method. Using Context, you can browse the resource file, database, etc.. The base class is AndroidTestCase, the common is its subclasses, and the specific components of Association.

Sub class:

Instrumentation system

Inherited from the JUnit class TestCase, and you can use the Instrumentation framework, is used to test Activity. The use of Instrumentation, Android can automatically send events to the UI test procedure, and can precisely control Activity start, monitoring of the Activity life cycle state.

The base class is InstrumentationTestCase. All subclasses of it can send button or touch events to UI. Subclasses can be injected into a simulation Intent.

Sub class:

Unlike other Instrumentation types, the test class cannot injection simulation Intent.

You can see the difference between these two, androidTestCase for activity has nothing to do with the test, such as the program logic, instrumentation is suitable for acitivity testing.

The first use of online examples:

The 1 begin to build a Android project, known as Sample, the code as follows:

package com.hustophone.sample;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Sample extends Activity {
    private TextView myText = null;
    private Button button = null;
    public void onCreate(Bundle savedInstanceState) {
        myText = (TextView) findViewById(;
        button = (Button) findViewById(;
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                myText.setText("Hello Android");
    public int add(int i, int j) {
        return (i + j);

The function of this procedure is relatively simple, click the button, the content of TextView was changed from Hello to Hello Android. at the same time, in this class, I wrote a simple add method, is not invoked, for testing purposes only.

2 in the SRC folder to add a test package, add a test class SampleTest test package

The following code test:

package com.hustophone.sample.test;
import com.hustophone.sample.R;
import com.hustophone.sample.Sample;
import android.content.Intent;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
public class SampleTest extends InstrumentationTestCase {
    private Sample sample = null;
    private Button button = null;
    private TextView text = null;
     * The initial setup
     * @see junit.framework.TestCase#setUp()
    protected void setUp()  {
        try {
        } catch (Exception e) {
        Intent intent = new Intent();
        intent.setClassName("com.hustophone.sample", Sample.class.getName());
        sample = (Sample) getInstrumentation().startActivitySync(intent);
        text = (TextView) sample.findViewById(;
        button = (Button) sample.findViewById(;
     * Waste disposal and resource recovery
     * @see android.test.InstrumentationTestCase#tearDown()
    protected void tearDown()  {
        try {
        } catch (Exception e) {
     * Function test
    public void testActivity() throws Exception {
        Log.v("testActivity", "test the Activity");
        getInstrumentation().runOnMainSync(new PerformClick(button));
        assertEquals("Hello Android", text.getText().toString());
     * Click on the button interface simulation
    private class PerformClick implements Runnable {
        Button btn;
        public PerformClick(Button button) {
            btn = button;
        public void run() {
     * Methods in the test class
    public void testAdd() throws Exception{
        String tag = "testAdd";
        Log.v(tag, "test the method");
        int test = sample.add(1, 1);
        assertEquals(2, test);

Here to explain the simple code:

setUp()And tearDown () are protected method, through inheritance can override these methods.

Has the following interpretation in the Android Developer

protected void setUp ()

Since: API Level 3

Sets up the fixture, for example, open a network connection. This method is called before a test is executed.

protected void tearDown ()

Since: API Level 3

Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.

setUp ()For the initial setting, such as a Activity start, initialize the resource etc.

tearDown ()To waste disposal and resource recovery.

In the testActivity () method in this test, I simulate a button click event, and procedures to determine whether in accordance with the expected execution. Here PerformClick this method inherits the Runnable interface, to perform the simulation event through the new thread, did so, because if the operation may block the UI thread directly on the UI thread.

2 to correctly perform the test, also need to modify the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.hustophone.sample" android:versionCode="1"
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!In introducing test library -->
        <uses-library android:name="android.test.runner" />
        <activity android:name=".Sample" android:label="@string/app_name">
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
    <uses-sdk android:minSdkVersion="3" />
    <!Objective -- indicates the name of the tested package with instrumentation. -->
    <instrumentation android:targetPackage="com.hustophone.sample" android:name="android.test.InstrumentationTestRunner" />

After the above steps, the following can start testing. Test method also has the following kinds, here are two commonly used methods:

(1) Eclipse integrated JUnit tool

Select the project Sample in Eclipse, right click, select Android JUnit Test in the Run as menu option

At the same time can view the information through the LogCat tool

(2) The use of Intellij IDEA or Android studio

Right click on your test project, or the test class, select Run, and then select the option robot icons, windows and almost Eclipse,

View information using LogCat.

Posted by Cynthia at November 20, 2013 - 9:46 AM