如何在Android中利用Instrumentation来进行测试(转载)

如何在Android中利用Instrumentation来进行测试?

51Testing软件测试网~}#BKW(W U

在介绍具体的命令之前,我们先理解一下单元测试的层次。一组单元测试可以被组织成若干个TestSuite。每个TestSuite包含若干TestCase(某个继承android.jar的junit.framework.TestCase的类)。每个TestCase又包含若干个Test(具体的test方法)。51Testing软件测试网z/U-Om,R

51Testing软件测试网6s#`-T{y.@^

如果假设com.android.foo是你的测试代码的包的根。当执行以下命令时,会执行所有的TestCase的所有Test。测试的对象就是在Target Package中指定的包中的代码:51Testing软件测试网2s [ M/P/fz k

51Testing软件测试网6`#`8w6fo~7A

adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网DG1h)sPvSR

0V Bq,l)|$Vo!w0如果你想运行一个TestSuite,首先继承android.jar的junit.framework.TestSuite类,实现一个TestSuite(比如叫com.android.foo.MyTestSuite),然后执行以下命令执行此TestSuite51Testing软件测试网JD$| Dq8zo$v7v

51Testing软件测试网{V^;r9{&NnPa

adb shell am instrument -e class com.android.foo.MyTestSuite -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网)lW(|2s+kV

&}I'Lyc(X$XL0其中的-e表示额外的参数,语法为-e [arg1] [value1] [arg2] [value2] …这里用到了class参数。

i.A}n}9WO/s0

Cb:V! I0如果仅仅想运行一个TestCase(比如叫com.android.foo.MyTestCase),则用以下命令:

e _^_,@X^1I051Testing软件测试网f7C!n:cn%]E

adb shell am instrument -e class com.android.foo.MyTestCase -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网"_ m%F,?(fhWp+V|

51Testing软件测试网1m7W:UOb

如果仅仅想运行一个Test(比如就是上面MyTestCase的testFoo方法),很类似的,就这样写:

d/uK0I|`0

!_QPHO g0adb shell am instrument -e class com.android.foo.MyTestCase#testFoo -w com.android.foo/android.test.InstrumentationTestRunner51Testing软件测试网i'z(Y:e m$w

,JV}lN'u3NI;k0然后,所有的测试结果会输出到控制台,并会做一系列统计,如标记为E的是Error,标记为F的是Failure,Success的测试则会标记为一个点。这和JUnit的语义一致。如果希望断点调试你的测试,只需要直接在代码上加上断点,然后将运行命令参数的-e后边附加上debug true后运行即可。更加详细的内容可以看InstrumentationTestRunner的Javadoc。我希望Android能尽快有正式的文档来介绍这个内容。51Testing软件测试网 M v/`l;D#}$[O-`Yk

如何在Android的单元测试中做标记?

51Testing软件测试网/u GIY5I3Xo

在android.test.annotation包里定义了几个annotation,包括@LargeTest,@MediumTest,@SmallTest,@Smoke,和@Suppress。你可以根据自己的需要用这些annotation来对自己的测试分类。在执行单元测试命令时,可以在-e参数后设置“size large”/ “size medium”/ “size small”来执行具有相应标记的测试。特别的@Supperss可以取消被标记的Test的执行。

原文地址:https://www.cnblogs.com/yaya1943/p/3290798.html