標籤:單元測試 android開發
假設已經實現了一個計算百分比功能需要測試,代碼:
public class ProgressService { public Integer getCurrentProgerss(double current, double max) { Integer i=(int)((current / max) * 100) ; return i; }}
要對指定功能進行單元測試,詳細步驟如下:
一 測試類別
編寫一個測試類別,來執行我們的功能,這個類需要繼承AndroidTestCase。
import android.test.AndroidTestCase;import android.util.Log;import com.example.service.ProgressService;public class ProgressServiceJUnit extends AndroidTestCase { private final String TAG="main"; public ProgressServiceJUnit() { // TODO Auto-generated constructor stub } public void getCurrentProgerssTest(){ ProgressService progressService=new ProgressService(); Integer pro=progressService.getCurrentProgerss(20, 70); Log.i(TAG, pro.toString()); }}
二 JUnit支援在AndroidManifest.xml中增加對JUnit的支援,並制定測試專案包。
1 <application>節點之前加入:
<uses-permission android:name="android.permission.RUN_INSTRUMENTATION" /> 添加許可權<instrumentationandroid:name="android.test.InstrumentationTestRunner" 固定類容 android:targetPackage="com.example.junittestdemo" > 要測試功能所在的包</instrumentation>
2 manifest.xml的<application>中加入:
<application>...<uses-library android:name="android.test.runner" /> ...<application/>
三 運行滑鼠左鍵在測試案例方法上,Run As→Android JUnit Test。
Android開發基礎之Eclipse單元測試