读书人

[android]android自动化测试10之单元测

发布时间: 2012-06-28 15:20:03 作者: rapoo

[android]android自动化测试十之单元测试实例
android源代码中每个app下中都自带了一个test用例,下面主要介绍下camra单元测试用例

在AndroidManifest.xml中标明了测试用例instrumentation函数入口

Java代码

   


camera启动性能测试
Java代码

  需要注意的是,在这里面我加上了:

  
Java代码



  以及:

  
Java代码

  Step 4.运行

  首先通过模拟器运行一下AndroidUT,然后在命令行终端中运行
Java代码


这样,在启动程序的时候就会先启动一个Application,然后在此Application运行过程中根据情况加载相应的 Activity,而Activity是需要一个界面的。但是Instrumentation并不是这样的。你可以将Instrumentation理解为一种没有图形界面的,具有启动能力的,用于监控其他类(用Target Package声明)的工具类。任何想成为Instrumentation的类必须继承android.app.Instrumentation。下面是这个类的解释:

Base class for implementing application instrumentation code. When running with instrumentation turned on, this class will be instantiated for you before any of the application code, allowing you to monitor all of the interaction the system has with the application. An Instrumentation implementation is described to the system through an AndroidManifest.xml's <instrumentation> tag.

对于单元测试,我们需要认真了解的就是android.test.InstrumentationTestRunner类。这是Android单元测试的主入口。它相当于JUnit当中TestRunner的作用。

那么如何加载它呢,首先要在manifest文件中加入一行关于Instrumentation的声明。比如Android Api Demos中的测试里的manifest是这么写的(我滤掉了所有的注释):

Java代码


如果用Eclipse的ADT插件(0.8版本以上),也可以用图形界面来添加,如下图:


编辑好manifest,就可以打包(build,可以用Eclipse ADT来做,也可以用aapt命令手工完成),然后安装到虚拟机上(用adb install命令)。之后就可以利用命令行的方式来加载你的单元测试了。在Android Shell中加载一个Instrumentation的方法是利用以下命令:

Java代码
adb shell am instrument w XXXXXX


其中-w是指定Instrumentation类的参数标志。一个简单的例子是:

Java代码

在这个文件中,我将Activity和Instrumentation的声明写到了一起,而没有像Apis Demo那样分开。请注意里面的<uses-library>标签。如果没有那句,在运行测试时会报告找不到TestRunner。这是由于 Android在build的时候只把需要的东西打包,所以你必须明确的告诉Android Builder这一点。 3. Build和Install

在Eclipse上,这两个步骤是一起完成的。只要点一下Run即可。只不过如果你不在Run Configuration里将安装后的Launch Action设为“Do Nothing”,就会自动运行一下你的MainActivity。对于我们,设为Do Nothing即可。如下图:


完成后,利用命令

Java代码

三、被测试的Activity代码
Java代码


Java代码
# E:\android\android-sdk-windows-1.5_pre\tools>adb shell am instrument -w cc.andro
# idos.activity/android.test.InstrumentationTestRunner
# 如果你配置了Android环境变量,直接使用:
# adb shell am instrument -w cc.androidos.activity/android.test.InstrumentationTestRunner
# 语法:adb shell am instrument -w <被测试的类的包名>/android.test.InstrumentationTestRunner


此篇引用原文地址:http://mintelong.iteye.com/blog/460903,尊重作者以及版权

读书人网 >Android

热点推荐