Android单元测试步骤
1.修改AndroidManifest.xml文件.
添加instrumentation节点.其中name是固定值,targetPackage为需要测试的类所在的包.如:
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.ahai.sqlitedemo"
在application节点下添加 <uses-library android:name="android.test.runner" />
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ahai.sqlitedemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.ahai.sqlitedemo" > </instrumentation> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.ahai.sqlitedemo.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> <uses-library android:name="android.test.runner" /> </application> </manifest>
2.编写测试类,继承自AndroidTestCase. 此类可以引用getContext等方法,非常方便. 如:
package com.ahai.sqlitedemo; import android.test.AndroidTestCase; import com.ahai.sqlitedemo.dao.PersonDao; public class SqlTestCase extends AndroidTestCase { public void insert() { Person person = new Person("xiaojiang"); PersonDao personDao = new PersonDao(getContext()); personDao.Insert(person); } }
3.测试代码,如测试insert方法,在Package Explorer中,右击-Run As-Android JUnit Test.
4.常见错误
(1)Test run failed: Unable to find instrumentation target package:
出现这个错误是由于manifest中指定的package值,与android:targetPackage不一致导致.需要将两个修改为一致,并将测试类移到其中再测试.