Android單元測試與日誌輸出

來源:互聯網
上載者:User

 

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視圖裡面添加一個過濾器,就可以迅速篩選出要看到的資訊:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.