Android之單元測試


在實際開發中,開發android軟件的過程需要不斷地進行測試。使用Junint測試框架,是正規Android開發的必用技術,在Junint中可以得到組件,可以模擬發送事件和檢測程序處理的正確性。單元測試是嵌入到項目中;也可以作為一個單獨的項目爭對某個具體項目進行測試。

 

第一步:首先在AndroidManifest.xml中加入下面紅色代碼:

 

<manifest xmlns:android="http://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 ="http://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);
    }

}  


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM