天天看點

使用Junit對Android應用進行單元測試

  本文假設讀者已經有一定的android基礎知識,并且已經安裝了eclipse和android sdk等開發工具。本文将指導讀者如何将android junit架構應用到android應用中去。本文還特别重點展示了如何測試android中的activity和如何識别程式中的錯誤。

  本文的示例代碼可以在http://code.google.com/p/simple-calc-unit-testing/中下載下傳

  步驟1 被測試的應用simplecalc概況

  在本文中,将以一個寫好了的應用simplecalc簡單電腦為例子進行講解。這個簡單電腦有兩個功能,允許使用者輸入兩個數并将它們相加或相乘,最後顯示結果,如下圖所示:

使用Junit對Android應用進行單元測試

  步驟2 simplecalc的的界面設計

  由于應用比較簡單,隻占一屏,是以我們在/res/layout/main.xml中設計如下代碼所示:

<linearlayout p="" <="" xmlns:android="http://schemas.android.com/apk/res/android" style="line-height: normal !important;">

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent">

<textview p="" <="" android:layout_width="fill_parent" style="line-height: normal !important;">

android:layout_height="wrap_content" android:text="@string/hello"

android:gravity="center_horizontal" android:textsize="48px"

android:padding="12px" />

<edittext p="" <="android:id="@+id/value1" android:layout_height="wrap_content" style="line-height: normal !important;">

android:hint="@string/hint1" android:inputtype="numberdecimal"

android:layout_width="fill_parent" android:textsize="48px">

<edittext p="" <="android:id="@+id/value2" android:layout_height="wrap_content" style="line-height: normal !important;">

android:hint="@string/hint2" android:inputtype="numberdecimal"

<framelayout p="" <="android:id="@+id/framelayout01" style="line-height: normal !important;">

android:layout_width="wrap_content" android:layout_height="wrap_content"

android:padding="12px" android:background="#ff0000">

<linearlayout p="" <="" android:id="@+id/linearlayout02" style="line-height: normal !important;">

android:orientation="horizontal" android:background="#000000"

android:padding="4px">

<textview p="" <="" android:layout_width="wrap_content" style="line-height: normal !important;">

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">

<button p=" android:id="@+id/addvalues" android:layout_height="wrap_content">

android:text="@string/add" android:textsize="32px"

android:layout_width="wrap_content">

<button p="" <=" android:id="@+id/multiplyvalues" android:layout_height="wrap_content">

android:text="@string/multiply" android:textsize="32px"

  簡單解析一下這個界面設計,我們使用了linearlayout,以使得控件能在垂直方向豎向排列。界面中包括了顯示标題“unit testing sample”的textview,兩個輸入數字的edittext控件,一個framelayout控件中包含了一個水準的linearlayout,在這個linearlayout包含了一個顯示結果的textview以及其提示文字“result”,注意的是framelayout的背景顔色設定為紅色,而linearlayou設定成了黑色背景。   

最新内容請見作者的github頁:http://qaseven.github.io/

繼續閱讀