Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AndroidTestCase 用法入門:setUp、測試方法與 tearDown 流程

編輯:關於 Android 程式設計

AndroidTestCase 是寫 Android 單元測試最直接的入口,整體流程就是 setUp → 測試方法 → tearDown。下面用一個最小範例說明。

一、測試類別:TestCase.java

package com.test.casei;

import android.test.AndroidTestCase;

import android.util.Log;

public class TestCase extends AndroidTestCase {

private static final String TAG = "TestCase";

@Override

protected void setUp() throws Exception {

super.setUp();

Log.i(TAG, "[setUp]");

}

public void doWorkTest(){

Log.i(TAG, "[doWorkTest]");

}

@Override

protected void tearDown() throws Exception {

super.tearDown();

Log.i(TAG, "[tearDown]");

}

}

二、AndroidManifest.xml 的兩處關鍵設定

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="https://schemas.android.com/apk/res/android"

package="com.test.casei"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" >

<uses-library android:name="android.test.runner" /><!-- 為測試添加 android.test.runner-->

</application>

<!-- 為測試添加 android.test.InstrumentationTestRunner -->

<instrumentation

android:name="android.test.InstrumentationTestRunner"

android:targetPackage="com.test.casei"

android:label="test"

/>

</manifest>

重點有兩個:application 節點中要補上 android.test.runner 這個 uses-library,manifest 下則要宣告 InstrumentationTestRunner 並透過 android:targetPackage 指向被測程式。

三、執行流程

setup() ------> doWorkTest() ----> tearDown()

也就是說,每個測試方法執行前都會先跑 setUp,跑完再走 tearDown,彼此之間不會互相污染狀態。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved