要在android中进行单元测试,主要分如下两步:
1.写一个测试类继承自android.test.AndroidTestCase
2.在AndroidManifest.xml文件中进行配置
步骤1代码:
package com.mmqzlj.test;
import com.mmqzlj.utils.DownloadText;
import android.test.AndroidTestCase;
public
class DownloadTextTest
extends AndroidTestCase {
public
void testDownload(){
DownloadText.test();
}
@Override
protected
void setUp()
throws Exception {
// TODO Auto-generated method stub
super.setUp();
}
@Override
protected
void tearDown()
throws Exception {
// TODO Auto-generated method stub
super.tearDown();
}
@Override
public
void testAndroidTestCaseSetupProperly() {
// TODO Auto-generated method stub
super.testAndroidTestCaseSetupProperly();
}
}
setUp() ,tearDown(),testAndroidTestCaseSetupProperly() 这3个方法都是覆写父类的。setUp()设置测试前须要执行的内容,好比创建一个链接等,tearDown()是在测试执行后须要进行的动做,好比关闭链接等。testAndroidTestCaseSetupProperly()主要用于检验测试所用参数。若是不须要这三个方法也能够不覆写。
步骤2代码:
<?
xml
version
="1.0"
encoding
="utf-8"
?>
<
manifest
xmlns:android
="http://schemas.android.com/apk/res/android"
package
="com.mmqzlj.activity"
android:versionCode
="1"
android:versionName
="1.0"
>
<
application
android:icon
="@drawable/icon"
android:label
="@string/app_name"
>
<
uses-library
android:name
="android.test.runner"
>
</
uses-library
>
<
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-permission
android:name
="android.permission.INTERNET"
/>
<
instrumentation
android:name
="android.test.InstrumentationTestRunner"
android:targetPackage
="com.mmqzlj.activity"
>
</
instrumentation
>
</
manifest
>
写好AndroidTestcase,而后就是在AndroidManifest.xml增长两句话。一是在
application 节点下增长
<
uses-library
android:name
="android.test.runner"
>
</
uses-library
>。二是增长
<
instrumentation
android:name
="android.test.InstrumentationTestRunner"
android:targetPackage
="com.mmqzlj.activity"
>
</
instrumentation
>
你们可能注意到了,我这里的DownloadTextTest是在com.mmqzlj.test这个package下面,为什么我写成
com.mmqzlj.activity。 答案是写成com.mmqzlj.test执行时会报找不到com.mmqzlj.test包错,估计跟xml最顶部配置的package包有关系。总之写成
com.mmqzlj.activity能顺利找到com.mmqzlj.test.DownloadTextTest而且执行以test开头的方法就是了。至于缘由,请有识之士告知。 好了,配置完毕以后,在eclipse中右键run as ->Android Junit Test就能够了。