AndroidTestCase
如果對要存取資源或者其他一些依賴於Activity上下文的操作進行單元測試,則需擴展AndroidTestCase接口(Extend this if you need to access Resources or other things that depend on Activity Context.)
1
2 public class testServiceApp extends AndroidTestCase
3 {
4 public void testXXX() throws Exception
5 {
6 //具體測試操作的代碼 ,可以對要測試的類,方法操作
7 //Log.i();
8 }
9 }
配置AndroidManifest.xml
在application標簽的內部即與Activity標簽同級的位置添加單元測試庫:
<uses-library android:name="android.test.runner" />
然后在與application標簽同級的位置添加下面的
1 <instrumentation android:name="android.test.InstrumentationTestRunner"
2 android:targetPackage="com.aven.unitTest" android:label="Tests for My App" />
其中:targetPackage="com.aven.unitTest"根據測試類所在位置而定,同時在很多教程中都有提到它必須和
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aven.unitTest"
這里面的包名一致.
測試
如果運行整個測試文件,則在資源導航按右擊文件,選擇“運行方式”--->“Android Junit Test”,如果僅僅運行某個測試函數,則將光標定位函數名右擊,選擇“運行方式”--->“Android Junit Test”,這樣Eclipse會將它們部署到Android模擬器上,在Junit窗口可以看到測試信息,紅色當然說明測試出現問題,根據提示查找問題就OK了。
日志輸出
為了方便查找在測試函數中可以使用Log來輸出某些信息,這樣程序運行時,就可以很清楚的知道那一段代碼沒有正常運行或者說沒有達到我們的預期目的。
關於這個Log,官方文檔是這么寫的
Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.
The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
也就是說我們通常使用他的三種方法,Log.v() Log.d() Log.i() Log.w() and Log.e() 來輸出信息,分別表示錯誤,警告,信息,調試,冗長。一般可以用Log.i() 來輸出信息。使用起來很方便,先給輸出取個標記,可以任意,下面的例子中字符串標記MyActivity被聲明為一個靜態的字符串常量,這也是官方推薦的通行寫法:
1 private static final String TAG = "MyActivity";
2 Log.v(TAG, "index=" + i);
然后在Logcat視圖里面添加一個過濾器,就可以迅速篩選出要看到的信息: