下面来简单讲解一下代码:
setUp()和tearDown()都是受保护的方法,通过继承可以覆写这些方法。
在android Developer中有如下的解释
protected void setUp ()
Since: API Level 3
Sets up the fixture, for example, open a network connection. This method is called before a test is executed.
protected void tearDown ()
Since: API Level 3
Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.
setUp ()用来初始设置,如启动一个Activity,初始化资源等。
tearDown ()则用来垃圾清理与资源回收。
在testActivity()这个测试方法中,我模拟了一个按钮点击事件,然后来判断程序是否按照预期的执行。在这里PerformClick这个方法继承了Runnable接口,通过新的线程来执行模拟事件,之所以这么做,是因为如果直接在UI线程中运行可能会阻滞UI线程。
3、要想正确地执行测试,还需要修改AndroidManifest.xml这个文件。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.hustophone.sample" 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=".Sample" 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="3" /> <!--表示被测试的目标包与instrumentation的名称。--> <instrumentation android:targetPackage="com.hustophone.sample" android:name="android.test.InstrumentationTestRunner" /> </manifest> |
经过以上步骤,下面可以开始测试了。测试方法也有以下几种,下面介绍两个常用的方法:
(1)用Eclipse集成的JUnit工具
在Eclipse中选择工程Sample,单击右键,在Run as子菜单选项中选择Android JUnit Test