在Android項目中進行單元測試只要做以下三個方面:
一、在項目資訊清單檔中進行如下配置
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.hnspi.test" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <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> <!--其中android:targetPackage="net.hnspi.test"為項目的包名 --> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="net.hnspi.test" android:label="Tests for My App" /></manifest>
二、測試類別繼承android.test.AndroidTestCase類
package net.hnspi.test;import junit.framework.Assert;import net.hnspi.service.PersonService;import android.test.AndroidTestCase;public class PersonServiceTest extends AndroidTestCase {public void testSave() throws Exception{PersonService ps = new PersonService() ;int t = ps.save() ;Assert.assertEquals(21, t) ; //測試傳回值}}
三、執行測試