Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

動手做 Android 應用單元測試:從配置到執行

單元測試在 Android 開發中幾乎是標配,它能驗證程式碼的處理是否正確。下面用一個刻意寫錯的小例子,把整個流程走一遍。

被測試的類別

先準備一個待測類別,其中刻意放了一段會出錯的程式:

package com.betest.test;

public class betest {

public int test() {
String in = "test";
int b = new Integer(in);

}
}

很明顯,把 "test" 轉成整數會拋出例外,這正是我們希望測試框架能抓到的問題。

在 AndroidManifest.xml 中掛上測試函式庫

因為要在 Android 專案裡跑單元測試,必須先在功能清單中宣告測試 runner:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.test.test"
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=".MainActivity"
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="8" />
<!-- 包名要去測試文檔包名相同 -->
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.test.test" />
</manifest>

關鍵就是這兩段:

<uses-library android:name="android.test.runner" />

<instrumentation android:name="android.test.InstrumentationTestRunner"
 android:targetPackage="com.test.test" />

其中 targetPackage 必須與待測程式的包名一致,否則測試會找不到目標。

撰寫測試類別

 package com.test.test;

import junit.framework.Assert;
import com.betest.test;
import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {


public void testtest() throws Throwable{
PersonService service = new PersonService();
service.test();//檢驗save()方法運行是否正常

}
}

測試類別繼承 AndroidTestCase,每個以 test 開頭的方法就是一個測試案例。

執行與看結果

在 outline 中找到對應的測試方法,按右鍵選擇 Android Junit Test,執行後錯誤原因會直接出現在日誌中——本例會看到 NumberFormatException,正好證實測試框架發揮了作用。

更多 Android 相關資訊見 Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved