BloggerAds

2011年12月23日 星期五

在Android上 利用Android JUnit 單元測試

1.設定 AndroidManifest.xml


a.在application層級中加入下列紅色行


<application android:icon="@drawable/apk_icon" android:label="@string/app_name">
     <uses-library android:name="android.test.runner" />
     ....


     ....
</application>


b.在</manifest>層級中加入下列紅色行


<manifest xmlns:android="http://schemas.android.com/apk/res/android"<application android:icon="@drawable/apk_icon" android:label="@string/app_name">


<uses-library android:name="android.test.runner" />
...


....

</application>



<instrumentation 


android:name="android.test.InstrumentationTestRunner"


android:targetPackage="你要測試的原程式碼所在的package


android:label="Tests for My App" />
</manifest>


 


 


2.加入測試碼


 


public class transform_operatorTest extends AndroidTestCase {


    


    protected void setUp() throws Exception {
       t=new transform_operator();
    }


    public void testTrandform() throws Throwable {
       Assert.assertTrue(1 + 1 == 2);
    }


 


}


a.必須繼承AndroidTestCase


b.setUp()就等於是測試類別的建構子 可以在裡面設定測試前要做的事


c.裡面方法必須 throws Throwable 且名稱是你的方法前面加上test (表示你要測試哪個方法)


d.Junit裡有很多方法 如上       


Assert.assertTrue(.....);


的意思是 如果括號裡面的值不等於true的話 測試會告訴你錯誤 


其他還有很多方法 如Assert.assertEquals 就是如果裡面的兩個值不相等 就傳出錯誤


在裡面用System.out的話 會顯示在LogCat裡 不要以為沒有喔