2011年10月3日 星期一

如何建立android unit test專案

前置作業:
1. 先建立要被測試的專案,假設要被測試的專案是com.myCompany.myHello.要被測試的class是MyHelloActivity.


2. 開始建立unit test project

步驟:
1. 在Eclipse 裡開新專案, new > project > Android > Android test Project.


2. 設定值如下說明
2.1. 假設test專案名稱為myTestProject.
2.2. 被測試專案為myHello.


3. 完成之後,會在eclipse的package explorer出現一個test專案,如下:


4. 接著新增加一個test case class,如下圖。
為什麼要用ActivityInstrumentationTestCase2,原文解釋:Android offers several, but the one that tests in the most realistic environment is ActivityInstrumentationTestCase2, so you will use it as the base class. Like all activity test case classes, ActivityInstrumentationTestCase2 offers convenience methods for interacting directly with the UI of the application under test.


5. 完成之後eclipse自動generate出一個myTestClass.java檔,請加入
import com.myCompany.MyHelloActivity;
並MyTestClass的建構子,如下:

這裡的”com.myCompany”指的是package name.,也就是告訴super class說,我要使用com.myCompany的MyHelloActivity的class.

6. 加入setUp() function,這個function是整個test project在開始test 程序之前會先被呼叫的,在這裡需要先確保需要使用到的變數都先被初始化。

在setUp()裡,也許你需要加上
setActivityInitialTouchMode(false);
如果在你的test procedure裡有送出一些key events,一定要將touch mode設定成off。如果沒有用到key events,可以不管這一行。

7. 加入preconditions() function,這個function是用來做前置測試用,先確保等一下要被呼叫的test functions裡面用到的變數,物件都是有用的資訊。跟setUp()作用很相似,Android development help裡面提到,preconditions只會被呼叫一次,但是setUp是每一個test function被呼叫之前都會先被執行一次。


8. 原文補充:The purpose of testing initial conditions is not the same as using setUp(). The JUnit setUp() runs once before each test method, and its purpose is to create a clean test environment. The initial conditions test runs once, and its purpose is to verify that the application under test is ready to be tested.

10. 最後加入要測試的functions,根據測試結果只要是test開頭的function都會被執行。


11. 執行unit test


12. 範例原始碼


13. 執行結果,如下圖。
根據這樣的資訊,我們可以知道在每個test procedure被執行之前,都會先呼叫setUp(),所以我們應該將變數的初始化放在這個地方。Android development裡面提到testPreconditions只會被執行一次,但是系統執行test開頭的的順序似乎是以function name的ascii順序來執行的。


14. 參考來源:
Android develop: http://developer.android.com/resources/tutorials/testing/helloandroid_test.html

沒有留言:

張貼留言