android 单元测试

来源:互联网 发布:java遍历json数组对象 编辑:程序博客网 时间:2024/06/04 18:41

额进入稍微大点的公司又是写文档又是写测试类,真麻烦。

今天讲一下android 单元测试

首先,我们来了解一下android的测试类的层次结构:

可以看出android中的测试方法主要有AndroidTextCase和InstrumentationTextCase。在这篇文章中,我将介绍Instrumentation这种测试方法,那么什么是Instrumentation?

Instrumentation和Activity有点类似,只不过Activity是需要一个界面的,而Instrumentation并不是这样的,我们可以将它理解为一种没有图形界面的,具有启动能力的,用于监控其他类(用Target Package声明)的工具类。

下面通过一个简单的例子来讲解Instrumentation的基本测试方法。

1.首先建立一个Android project,类名为Sample,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
packagecom.hustophone.sample;
  
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.TextView;
  
publicclass Sample extendsActivity {
    privateTextView myText = null;
    privateButton button = null;
  
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myText = (TextView) findViewById(R.id.text1);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(newOnClickListener() {
            @Override
            publicvoid onClick(View arg0) {
                myText.setText("Hello Android");
            }
        });
    }
  
    publicint add(inti, intj) {
        return(i + j);
    }
}

这个程序的功能比较简单,点击按钮之后,TextView的内容由Hello变为Hello Android.同时,在这个类中,我还写了一个简单的add方法,没有被调用,仅供测试而已。

2. 在src文件夹中添加一个测试包,在测试包中添加一个测试类SampleTest

测试类的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
packagecom.hustophone.sample.test;
  
importcom.hustophone.sample.R;
importcom.hustophone.sample.Sample;
importandroid.content.Intent;
importandroid.os.SystemClock;
importandroid.test.InstrumentationTestCase;
importandroid.util.Log;
importandroid.widget.Button;
importandroid.widget.TextView;
  
publicclass SampleTest extendsInstrumentationTestCase {
    privateSample sample = null;
    privateButton button = null;
    privateTextView text = null;
  
    /*
     * 初始设置
     * @see junit.framework.TestCase#setUp()
     */
    @Override
    protectedvoid setUp()  {
        try{
            super.setUp();
        }catch(Exception e) {
            e.printStackTrace();
        }
        Intent intent = newIntent();
        intent.setClassName("com.hustophone.sample", Sample.class.getName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        sample = (Sample) getInstrumentation().startActivitySync(intent);
        text = (TextView) sample.findViewById(R.id.text1);
        button = (Button) sample.findViewById(R.id.button1);
    }
  
    /*
     * 垃圾清理与资源回收
     * @see android.test.InstrumentationTestCase#tearDown()
     */
    @Override
    protectedvoid tearDown()  {
        sample.finish();
        try{
            super.tearDown();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
  
    /*
     * 活动功能测试
     */
    publicvoid testActivity() throwsException {
        Log.v("testActivity","test the Activity");
        SystemClock.sleep(1500);
        getInstrumentation().runOnMainSync(newPerformClick(button));
        SystemClock.sleep(3000);
        assertEquals("Hello Android", text.getText().toString());
    }
  
    /*
     * 模拟按钮点击的接口
     */
    privateclass PerformClick implementsRunnable {
        Button btn;
        publicPerformClick(Button button) {
            btn = button;
        }
  
        publicvoid run() {
            btn.performClick();
        }
    }
  
    /*
     * 测试类中的方法
     */
    publicvoid testAdd() throwsException{
        String tag = "testAdd";
        Log.v(tag,"test the method");
        inttest = sample.add(1,1);
        assertEquals(2, test);
    }
}

下面来简单讲解一下代码:
setUp()和tearDown()都是受保护的方法,通过继承可以覆写这些方法。

在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 ()用来初始设置,如启动一个Activity,初始化资源等。
tearDown ()则用来垃圾清理与资源回收。

在testActivity()这个测试方法中,我模拟了一个按钮点击事件,然后来判断程序是否按照预期的执行。在这里PerformClick这个方法继承了Runnable接口,通过新的线程来执行模拟事件,之所以这么做,是因为如果直接在UI线程中运行可能会阻滞UI线程。

2.要想正确地执行测试,还需要修改AndroidManifest.xml这个文件.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hustophone.sample"android:versionCode="1"
    android:versionName="1.0">
    <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
        <!--用于引入测试库-->
        <uses-libraryandroid:name="android.test.runner"/>
        <activityandroid:name=".Sample"android:label="@string/app_name">
           <intent-filter>
              <actionandroid:name="android.intent.action.MAIN"/>
              <categoryandroid:name="android.intent.category.LAUNCHER"/>
           </intent-filter>
       </activity>
    </application>
  
    <uses-sdkandroid:minSdkVersion="3"/>
    <!--表示被测试的目标包与instrumentation的名称。-->
    <instrumentationandroid:targetPackage="com.hustophone.sample"android:name="android.test.InstrumentationTestRunner"/>
</manifest>

经过以上步骤,下面可以开始测试了。测试方法也有以下几种,下面介绍两个常用的方法:

(1) 用Eclipse集成的JUnit工具
在Eclipse中选择工程Sample,单击右键,在Run as子菜单选项中选择Android JUnit Test


0 0