編輯:關於 Android 程式設計
本文通過一個簡單實例,帶大家快速上手 Android 的單元測試。在實際開發中,Android 應用需要反覆測試,而 JUnit 是正規開發中的必備技術——它能獲取組件、模擬發送事件並驗證程序處理的正確性。單元測試既可以嵌入項目內部,也可以作為獨立工程針對某個項目進行測試。
首先在清單文件中加入測試相關的庫引用與 instrumentation 配置:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.lee0000.test" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner"/>
</application>
<use-sdk android:minSdkVersion="6"/>
<instrumentation android:name="android.test.instrumentationTestRunner" android:targetPackage="com.lee0000.test" android:label="Tests"/>
***注意:上面 targetPackage 指定的包要和應用的 package 相同。
一般把待測試的方法命名為 testXXX 的形式。測試時在 Outline(大綱)視圖中選中測試方法,右鍵選擇 Run As → Android Junit Test 即可。
項目結構如下:

AndroidManifest.xml 文件:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.lee0000.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".JUintTestActivity" 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> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.lee0000.test" android:label="Tests"/> </manifest>
先定義兩個待測試的方法:
public class testclass { public void str(String s){ System.out.println(s.substring(6)); } public int add(int a,int b){ return a+b; } }
測試類一般繼承 AndroidTestCase,測試時針對這兩個方法進行。如果在對應方法中選擇 Run As → Android Junit Test 時出錯,可以右鍵點擊 Test 類,選擇 Run As → Run Configurations,在 Instrumentation runner 中進行相應配置:
import junit.framework.Assert; import android.test.AndroidTestCase; public class Test extends AndroidTestCase{ public void teststr() throws Exception{ testclass tc = new testclass(); tc.str("null"); } public void testadd(){ testclass tc = new testclass(); int t = tc.add(1, 2); Assert.assertEquals(3, t); } }
以上就是 Android 單元測試的基本入門流程,希望能對大家的學習有所幫助。
Android 自定義倒計時 View 實作全解析
本篇將手把手帶你實作一個帶陰影、帶指引小圓點的自定義倒計時 View。別被效果圖嚇到,真正的難點其實只有「白色小圓圈的動態定位」一處,其餘都是自定義 View 中常見的知
解決難題:防止 App 在後台被殺後點擊桌面圖標重新啟動
項目中曾遇到一個百思不得其解的問題:在 app 使用過程中按了 home 鍵,然後去看看微信之類的其他應用,這時再點擊 app 的桌面圖標,app 卻是重新啟動的,而不是
Android 來電攔截實戰:反射 + AIDL + 內容觀察者實現黑名單
當我們想要屏蔽一些莫名的陌生號碼時,就需要具備來電攔截與通話記錄刪除的能力。攔截的核心業務邏輯主要在一個後台服務中完成,包括兩部分:一是註冊電話監聽,二是取消註冊監聽(這
5555 端口被佔用導致模擬器無法識別的解決方法
「昨天模擬器還好好的,今天 Eclipse 突然就識別不了了。」——這個問題困擾過不少 Android 開發者。排查之後發現,罪魁禍首往往是某個手機助手類軟件:它們為了實