Android单元测试实践 (成功运行)
上一篇 / 下一篇 2009-12-01 21:22:44 / 个人分类:Android
我的栏目
- 栏目:Android
]biu:dS|0
任何程序的开发都离不开单元测试来保证其健壮和稳定。Android的程序自然也不例外。从Android SDK 0.9开始,就有了比较成熟的测试框架,但是直到目前最新的1.1版本,也没有详细的文档介绍这个内容,只是简单的给了一个Api Demos里的几个单元测试代码。因此,我在这里对此内容做一下梳理和总结:51Testing软件测试网_0Q6G0v*] i o:k(|+h
JUnit还能用么?
5J'ey+?3m0在Java下做单元测试必然用到JUnit。这里说的JUnit是指从Apache基金会下载的junit.jar里提供的一系列单元测试功能。这些功能显然是运行在JDK之上的。在Android下已经没有了JDK,自然也无法运行JUnit。但是这并不妨碍我们利用JUnit编写单元测试。只不过在运行单元测试时,一定要用JDK来运行,利用java命令来启动JUnit的某个Runner。如果是用Eclipse的话,可以在Run Configuration里新建一个JUnit。但是一定要记得在Classpath选项卡里将Bootstrap Entries中的Android Library改成JRE,并且添加junit.jar。
V.m D#\@0!f$_5x!C6F051Testing软件测试网T7[[8bu(g a/|
+zL&Z#ZSq0很明显的,这种测试就是正规的Java单元测试,和Android没有任何关系。你无法测试任何关于Android系统中的API,你写的Activity,人机界面等等。所以,如果你想测试仅仅是一些封装数据的对象,或者是纯粹的数值计算,还是可以用这种方法的。51Testing软件测试网2uN_k k3ij$e }
Android里面的junit.framework包是怎么回事?
51Testing软件测试网-I1?JQ5N{5dE/f&I很多人看到这个包的时候,第一反应是Android是不是已经完整集成了JUnit。很遗憾这不是事实。如果你按照JUnit的运行方法,却不像上面那样改用JDK,就一定会得到一个异常:51Testing软件测试网7yhujXrz k
51Testing软件测试网 _{ rP4Vkt&ECZ+H#51Testing软件测试网c*t&d%}e,b X.C
# An unexpected error has been detected by Java Runtime Environment:
Tx pd5b5BQ*}(Ks8I0#51Testing软件测试网
Nh s:Z!['H5Q%^Q
# Internal Error (classFileParser.cpp:2924), pid=4900, tid=4476
1A~@d:n-y+Y@T0#Error: ShouldNotReachHere()
;r*KI`
l Sc0#
2^,U-Y6l"O)a6tR7Z5g0# Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode windows-x86)
;Q:|q M8|5fzM0# An error report file with more information is saved as:51Testing软件测试网2I/m*^5w
cD#cag
U
# E:\Mydoc\EclipseWorkspace\TestAndroid\hs_err_pid4900.log51Testing软件测试网5_){/JZ#z\#rQ
#51Testing软件测试网m
Lbga&\5@J*o
# If you would like to submit a bug report, please visit:
p#~4Sw/z`/p0# http://java.sun.com/webapps/bugreport/crash.jsp
M^7Q'Vi3D5HF0#
实际上,TestCase这个类用于在Android担当所有独特的TestCase的基类的作用,它是一个Abstract Class。Android单元测试类继承关系图如下所示:51Testing软件测试网7m vWop
6?/e"j gj\0h}n8T2RFO0之所以有那么多XXXTestCase主要是为了简化工作。例如当你想对一个访问数据库的功能进行测试时,首先需要自己启动并初始化数据库。在这里是类似的,如果你想测试一个Activity,首先要启动它。而ActivityTestCase就会自动帮你做完这些事情。而ActivityUnitTestCase会更注重测试的独立性,它会让测试与Android底层的联系降到最低。其余的类可以查看相关的Javadoc来按需挑选。要编写测试,就是找到合适的XXXTestCase作为基类来继承,并且编写自己的测试方法。
{u0M5Oi/l0"t Io*O;M C0很明显的,最简单的编写测试的方法就是继承AndroidTestCase写一个自己的TestCase。然后为自己的一组TestCase写一个Activity界面,由界面控制TestCase的启动,运行和结果报告。但是,你很快会发现,为何要给测试写一个界面呢?这太诡异了。这时就需要一种技术,它可以利用命令行(Shell)来启动一组测试,并且通过命令行的形式给出结果。这就是所谓的Instrumentation。
y9wN#sA2ii)hV0什么是Instrumentation?
Y.\6c(g fuc/\0一般在开发Android程序的时候,需要写一个manifest文件,其结构是:51Testing软件测试网h0U*L m8jf A,^&ff
51Testing软件测试网;Mh%_2]!P1dv1As5W<application android:icon="@drawable/icon" android:label="@string/app_name">
%n(Z lx$wd,S9O4LB051Testing软件测试网)aw#b-Ca` ^-cU<activity android:name=".TestApp" android:label="@string/app_name">
"M$x.kVi3n'k051Testing软件测试网:M9h;?/B4C`……
e`'a p3lB[C051Testing软件测试网DaK-S6jn.hAp</activity>51Testing软件测试网4a+n4|9b7|Sh4u
51Testing软件测试网,{-n E(h ud</application>51Testing软件测试网*zS;qc@0Q*gEK8[
51Testing软件测试网;Q4p'A,T+rAqX:d这样,在启动程序的时候就会先启动一个Application,然后在此Application运行过程中根据情况加载相应的Activity,而Activity是需要一个界面的。但是Instrumentation并不是这样的。你可以将Instrumentation理解为一种没有图形界面的,具有启动能力的,用于监控其他类(用Target Package声明)的工具类。任何想成为Instrumentation的类必须继承android.app.Instrumentation。下面是这个类的解释:51Testing软件测试网7f#Je-{Ao
T rfifI0Base 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.
'U9b"F+a%X%hmU0O;xI?Q$`%Zf[ {0对于单元测试,我们需要认真了解的就是android.test.InstrumentationTestRunner类。这是Android单元测试的主入口。它相当于JUnit当中TestRunner的作用。51Testing软件测试网6]$~)W EA
]3s8s,_x Dn!FV0那么如何加载它呢,首先要在manifest文件中加入一行关于Instrumentation的声明。比如Android Api Demos中的测试里的manifest是这么写的(我滤掉了所有的注释):51Testing软件测试网-e-L'a;Yg7n,?;a
51Testing软件测试网rof7lCBNHdH<manifest xmlns:android="http://schemas.android.com/apk/res/android"
;r;q&A7k1o6{b04D1kj9My(a(@0@;~~0V A0package="com.example.android.apis.tests">51Testing软件测试网 @!jY/xKDVK
-T\D'v9Q{m;b*N.U;}0<application>
J-i,NG{/PRQ,X/P051Testing软件测试网%Jcn5ofg/f\m<uses-library android:name="android.test.runner" />51Testing软件测试网"]VHE!tKq
51Testing软件测试网"L6~%Y bW</application>
j(G"g;Xs-?0q0_"GD\-pn0<instrumentation android:name="android.test.InstrumentationTestRunner"
&AO-o;s#t@;]8Dm;X0SP8y DM'z$v8{0android:targetPackage="com.example.android.apis"
g gk.dndf4zF0xJ yJ~qi0android:label="Tests for Api Demos."/>51Testing软件测试网5M~(_ Nn
n2^4T.MS2`0</manifest>51Testing软件测试网 kC@D,q?:bq#_
51Testing软件测试网T e9?n-Z%o Ry{n如果用Eclipse的ADT插件(0.8版本以上),也可以用图形界面来添加,如下图:
9n4kh'|pz5M2W&Ho#S0*~:p;dnnFf"o05~;\%C.C"n-v"a0编辑好manifest,就可以打包(build,可以用Eclipse ADT来做,也可以用aapt命令手工完成),然后安装到虚拟机上(用adb install命令)。之后就可以利用命令行的方式来加载你的单元测试了。在Android Shell中加载一个Instrumentation的方法是利用以下命令:
3GE_x8jf1c051Testing软件测试网6VxEN padb shell am instrument –w XXXXXX
luN9d"~J051Testing软件测试网#H!BTh(k zGH其中-w是指定Instrumentation类的参数标志。一个简单的例子是:
`#y t3qu f:U0:}+UNyVWs+j g:SY0adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网H^ SWj
51Testing软件测试网G}4Z+gS%oQ当然,也可以利用adb shell先进入android命令行模式,再直接写am instrument –w XXXXXXX。下面将具体介绍如何将根据需要加载一组单元测试。
exEW+[ p1?tt0如何在Android中利用Instrumentation来进行测试?
51Testing软件测试网9u(]TD,BQ7M在介绍具体的命令之前,我们先理解一下单元测试的层次。一组单元测试可以被组织成若干个TestSuite。每个TestSuite包含若干TestCase(某个继承android.jar的junit.framework.TestCase的类)。每个TestCase又包含若干个Test(具体的test方法)。51Testing软件测试网YSL$@Q
51Testing软件测试网1jC:X[u2Z'_2vSM如果假设com.android.foo是你的测试代码的包的根。当执行以下命令时,会执行所有的TestCase的所有Test。测试的对象就是在Target Package中指定的包中的代码:
$Vd4dmo1D;s051Testing软件测试网5[ t|#AYwadb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner
:r;v2\;e]"a1o0Mz"ubO0如果你想运行一个TestSuite,首先继承android.jar的junit.framework.TestSuite类,实现一个TestSuite(比如叫com.android.foo.MyTestSuite),然后执行以下命令执行此TestSuite51Testing软件测试网'Nq Bfc2w&\W
!^f D^Va0adb shell am instrument -e class com.android.foo.MyTestSuite -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网G'w)K-Q1p,Z
51Testing软件测试网6a%Jx6KX)z其中的-e表示额外的参数,语法为-e [arg1] [value1] [arg2] [value2] …这里用到了class参数。
s0Ae-gh ~/M3t o;lD051Testing软件测试网$y;Q v ^u(L |]N如果仅仅想运行一个TestCase(比如叫com.android.foo.MyTestCase),则用以下命令:51Testing软件测试网&o1{ o?!v1S
g cYY9KF3B.Xxk.kN0adb shell am instrument -e class com.android.foo.MyTestCase -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网9m8]`'a`
"P.F @{Jpn0如果仅仅想运行一个Test(比如就是上面MyTestCase的testFoo方法),很类似的,就这样写:
gFZCc6b+@"E051Testing软件测试网g/oZyUo]adb shell am instrument -e class com.android.foo.MyTestCase#testFoo -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网VAQc(^
E"PCJZfR-}'oF0然后,所有的测试结果会输出到控制台,并会做一系列统计,如标记为E的是Error,标记为F的是Failure,Success的测试则会标记为一个点。这和JUnit的语义一致。如果希望断点调试你的测试,只需要直接在代码上加上断点,然后将运行命令参数的-e后边附加上debug true后运行即可。更加详细的内容可以看InstrumentationTestRunner的Javadoc。我希望Android能尽快有正式的文档来介绍这个内容。
:B#s2Y|qi-nMA0如何在Android的单元测试中做标记?
51Testing软件测试网H'om Ps在android.test.annotation包里定义了几个annotation,包括@LargeTest,@MediumTest,@SmallTest,@Smoke,和@Suppress。你可以根据自己的需要用这些annotation来对自己的测试分类。在执行单元测试命令时,可以在-e参数后设置“size large”/ “size medium”/ “size small”来执行具有相应标记的测试。特别的@Supperss可以取消被标记的Test的执行。51Testing软件测试网*wfs A3H8j
完整的操作过程
51Testing软件测试网v4s2ZJ1`3|总结以上所有的内容,编写并运行完整的测试需要以下的步骤:
@zP W;k1U051Testing软件测试网I$_'Rl.z$x(R:pG%Ce4I$D0k"w SG8m*E w/oD1K9pl0以上步骤中,在Android自带的例子中,我发现它有两个manifest.xml。也就是说在步骤3中源代码和测试代码分别生成了两个不同的包。然后步骤4利用adb install命令安装到了虚拟机上。由于我没有找到Eclipse ADT有办法可以为一个只有Instrumentation,没有Activity的Application打包并安装,于是采用了略微不同的办法完成了这个工作。下面将一一详细介绍整个过程。
e c6b4O,He(]2y01. 编写程序
1JDI/{.X d@9v!r0我新建了一个项目TestApp,参数为:51Testing软件测试网&gg4O)xLM1kVpk
M n SX%u!HO_0Package Name: com.android.testapp51Testing软件测试网 }qY-\R!NLK|
51Testing软件测试网hZd8f!yAXVvActivity Name: MainActivity51Testing软件测试网M9SM-rmM`-rZ
MkC+w&\s o&p^0Application Name: TestApp
8BTv-[y B&q g:W0r2y:I+?Q0以下是MainActivity的源代码:51Testing软件测试网/yn8J&vS7I){m2r
51Testing软件测试网@Z._({z`D&~x7K/XxUW0
%v6E&\(Aoj+xb ?0packagecom.android.testapp;51Testing软件测试网,d*d3M @[X+|'~,eZs
nOY a Q^#S']OY0importandroid.app.Activity;
4ERZw+o0PU051Testing软件测试网Z.ZKfG)mQr Himportandroid.os.Bundle;51Testing软件测试网QVF1t.K*^iv2d!Y|
:bkt ~(aS/X8F0publicclassMainActivityextendsActivity {51Testing软件测试网T [q3c;D;R-Q@ q!D
51Testing软件测试网(i~#[GzN5s4rq/** Called when the activity is first created. */
6M1W~ P!^M0/v1n/q0yG y0@Override
|}|uj051Testing软件测试网0R*{e(?_9x9TpublicvoidonCreate(Bundle savedInstanceState) {51Testing软件测试网 [Ak:P(uE.m/^'{(q
51Testing软件测试网u3_3n;H7y#Issuper.onCreate(savedInstanceState);
(~$yx,C(H m051Testing软件测试网OLD3z3d'kdsetContentView(R.layout.main);51Testing软件测试网9uM7}a2Sl
)y&k7m+rK8]:A*n$u0}51Testing软件测试网QC#L!{h~`*`8@Q
R(B-aX@`Pd0publicintsum(inta,intb) {51Testing软件测试网$bFw^eT8A2C-l`
51Testing软件测试网_*?mA*R@J#rreturna + b;
P u/`7pJK&`8k051Testing软件测试网V![(LF#?K}
z Z!U-u-B!t051Testing软件测试网 e(t7j L'[oOZ }publicintsubstract(inta,intb) {
}5j^XNtf8Q051Testing软件测试网 rxJh(y'v6d+RK2j Qreturnb - a;51Testing软件测试网"~lh$@U ED7R2B/@
51Testing软件测试网by`7]a'\}51Testing软件测试网d6\Xa|$c%Oe3D,p
51Testing软件测试网$gTY#@h'S@3k)v'X}
.A7M/T"[*Kq0?0.jI#utc&K p$v0其中,我故意将减法的a – b写成了b – a。
:ifldVV~Y`02. 编写测试程序
K1plsdnF0然后,我新建了一个Source Folder,名为test,并在里面新建了包com.android.testapp.test。并定义了一个TestCase,名为TestMainActivity,源代码如下:51Testing软件测试网x#g&E5qn9^G&ZY H*F
51Testing软件测试网5t:t(a U*Epackagecom.android.testapp.test;51Testing软件测试网kZ6{"U'G;Y8I!\
51Testing软件测试网/I&KIn3H;B*Y^importcom.android.testapp.MainActivity;
P0e/@YIr-z%B$pDX0(` H[!w'zw0L9]0importandroid.test.ActivityInstrumentationTestCase2;
U5P^B vgp2zH/k0v:o4p~0Ty#U0importandroid.test.suitebuilder.annotation.MediumTest;
LFq#T`051Testing软件测试网R:b\3a p.bZ2^bcO5MpublicclassTestMainActivityextendsActivityInstrumentationTestCase2<MainActivity> {51Testing软件测试网mK B%ZE*t
51Testing软件测试网4U0@QJV&topublicTestMainActivity() {
x)q`-_6k,a051Testing软件测试网t-uE"{I#cM0Usuper("com.android.testapp", MainActivity.class);
yG[}-j9g0};b(}B*@0}
m)NsO#VqSo051Testing软件测试网&B7WQRqH,opublicTestMainActivity(String pkg, Class<MainActivity> activityClass) {51Testing软件测试网W9e7]*P K(d x
%wT;e)v`"z0super(pkg, activityClass);51Testing软件测试网 t*U0H2s$^^Q kY
51Testing软件测试网)Wb]:Pb G#qM*yOP}