天天看点

使用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/

继续阅读