在本文中,你將會(huì )學(xué)習到如何在Eclipse中創(chuàng )建Android JUnit的單元測試工程以及在不同的條件下創(chuàng )建及運行自動(dòng)測試用例。
準備工作
本文假設讀者已經(jīng)有一定的Android基礎知識,并且已經(jīng)安裝了Eclipse和Android SDK等開(kāi)發(fā)工具。本文將指導讀者如何將Android Junit框架應用到Android應用中去。本文還特別重點(diǎn)展示了如何測試Android中的Activity和如何識別程序中的錯誤。
本文的示例代碼可以在http://code.google.com/p/simple-calc-unit-testing/中下載
步驟1 被測試的應用SimpleCalc概況
在本文中,將以一個(gè)寫(xiě)好了的應用SimpleCalc簡(jiǎn)單計算器為例子進(jìn)行講解。這個(gè)簡(jiǎn)單計算器有兩個(gè)功能,允許用戶(hù)輸入兩個(gè)數并將它們相加或相乘,最后顯示結果,如下圖所示:

▲
步驟2 SimpleCalc的的界面設計
由于應用比較簡(jiǎn)單,只占一屏,所以我們在/res/layout/main.xml中設計如下代碼所示:
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_height="wrap_content" android:text="@string/hello"
android:gravity="center_horizontal" android:textSize="48px"
android:padding="12px" />
android:hint="@string/hint1" android:inputType="numberDecimal"
android:layout_width="fill_parent" android:textSize="48px">
android:hint="@string/hint2" android:inputType="numberDecimal"
android:layout_width="fill_parent" android:textSize="48px">
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:padding="12px" android:background="#ff0000">
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal" android:background="#000000"
android:padding="4px">
android:layout_height="wrap_content" android:text="@string/resultLabel"
android:textSize="48px" android:id="@+id/resultLabel">
android:layout_height="wrap_content" android:id="@+id/result"
android:textSize="48px" android:textStyle="bold"
android:layout_marginLeft="16px">
android:layout_height="wrap_content" android:layout_width="fill_parent">
簡(jiǎn)單解析一下這個(gè)界面設計,我們使用了LinearLayout,以使得控件能在垂直方向豎向排列。界面中包括了顯示標題“Unit Testing Sample”的textview,兩個(gè)輸入數字的edittext控件,一個(gè)FrameLayout控件中包含了一個(gè)水平的LinearLayout,在這個(gè)LinearLayout包含了一個(gè)顯示結果的textview以及其提示文字“Result”,注意的是FrameLayout的背景顏色設置為紅色,而LinearLayou設置成了黑色背景。
文章來(lái)源于領(lǐng)測軟件測試網(wǎng) http://kjueaiud.com/