Android單元測試初探——JunitTest



學習Android有一段時間了,雖然前段時間對軟件測試有了一些瞭解,不過接觸android的單元測試卻是頭一次。這幾天在物流大賽上也用了不少時間,所以對於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
package com.hustophone.sample;
  
import android.app.Activity;
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;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myText = (TextView) findViewById(R.id.text1);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                myText.setText("Hello Android");
            }
        });
    }
  
    public int add(int i, int j) {
        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
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;
  
    /*
     * 初始設置
     * @see junit.framework.TestCase#setUp()
     */
    @Override
    protected void setUp()  {
        try {
            super.setUp();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent intent = new Intent();
        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
    protected void tearDown()  {
        sample.finish();
        try {
            super.tearDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  
    /*
     * 活動功能測試
     */
    public void testActivity() throws Exception {
        Log.v("testActivity", "test the Activity");
        SystemClock.sleep(1500);
        getInstrumentation().runOnMainSync(new PerformClick(button));
        SystemClock.sleep(3000);
        assertEquals("Hello Android", text.getText().toString());
    }
  
    /*
     * 模擬按鈕點擊的接口
     */
    private class PerformClick implements Runnable {
        Button btn;
        public PerformClick(Button button) {
            btn = button;
        }
  
        public void run() {
            btn.performClick();
        }
    }
  
    /*
     * 測試類中的方法
     */
    public void testAdd() throws Exception{
        String tag = "testAdd";
        Log.v(tag, "test the method");
        int test = 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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hustophone.sample" android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!--用於引入測試庫-->
        <uses-library android:name="android.test.runner" />
        <activity android:name=".Sample" android:label="@string/app_name">
           <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
    </application>
  
    <uses-sdk android:minSdkVersion="3" />
    <!--表示被測試的目標包與instrumentation的名稱。-->
    <instrumentation android:targetPackage="com.hustophone.sample" android:name="android.test.InstrumentationTestRunner" />
</manifest>

經過以上步驟,下面可以開始測試了。測試方法也有以下幾種,下面介紹兩個常用的方法:

(1) 用Eclipse集成的JUnit工具
在Eclipse中選擇工程Sample,單擊右鍵,在Run as子菜單選項中選擇Android JUnit Test

同時可以通過LogCat工具查看信息

(2) 通過模擬器運行單元測試

點擊模擬器界面的Dev Tools菜單

再點擊Instrumentation選項,進入Instrumentation菜單

這裏有一個InstrumentationTestRunner,它是測試的入口,點擊這個選項,就可以自動運行我們的測試代碼。以下爲運行結果:

按鈕點擊前

按鈕點擊後

至此,一個簡單的測試過程結束了。當然,android的測試內容還有很多,也有比較複雜的,我會在以後的學習過程中繼續分享我的體會。好了,今天就到這裏吧!

鑑客鑑客
發帖於 4年前
9回/64360閱

按票數排序  顯示最新答案  共有9個答案 (最後回答: 11個月前 )

    0
  • 王東澤
    樓主,有人問題想問下。這樣做單元測試的好處是神馬呢?   就是簡化錯左嗎。易於查找錯誤
    --- 共有 1 條評論 ---
    • libz下功夫做單元測試,就會有許多測試用例,用來驗證程序是否實現了預定的功能;通過樓主提供的方式,把每個測試用例儘可能的通過代碼來實現,實現執行過程,可以很方便的執行測試過程
發佈了60 篇原創文章 · 獲贊 6 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章