如何用Android InstrumentationTestRunner 执行单个case

命令行demo如下:

adb shell am instrument -e class com.autonavi.MinimapAutomationTool#testLayerCancelButton -w com.autonavi/android.test.InstrumentationTestRunner

命令解析:

 

start an Instrumentation: am instrument [flags] <COMPONENT>

    -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)

    -e <NAME> <VALUE>: set argument <NAME> to <VALUE>

    -p <FILE>: write profiling data to <FILE>

    -w: wait for instrumentation to finish before returning

 

-e后面加参数 class就可以指定一个测试类,里面包含了若干个测试方法。

按照android帮助文档里面的名称,testsuite包含了若干个testcase,一个testcase其实就是一个测试类。

比如:Run the instrumentation using "adb shell am instrument -w", with the argument ‘-e class‘ set to run an individual .

如果想指定只执行某一个测试方法,就需要用#testxxx.第一个命令行demo.

有时候也可以用$符号,但是有什么区别,没有去研究。

以下是一些copy来的文档,个人觉得比较有用:

 

 

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

  如果假设com.android.foo是你的测试代码的包的根。当执行以下命令时,会执行所有的TestCase的所有Test。测试的对象就是在Target Package中指定的包中的代码:

  adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner

  如果你想运行一个TestSuite,首先继承android.jar的junit.framework.TestSuite类,实现一个 TestSuite(比如叫com.android.foo.MyTestSuite),然后执行以下命令执行此TestSuite

  adb shell am instrument -e class com.android.foo.MyTestSuite -w com.android.foo/android.test.InstrumentationTestRunner

  其中的-e表示额外的参数,语法为-e [arg1] [value1] [arg2] [value2] …这里用到了class参数。

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

  adb shell am instrument -e class com.android.foo.MyTestCase -w com.android.foo/android.test.InstrumentationTestRunner

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

  adb shell am instrument -e class com.android.foo.MyTestCase#testFoo -w com.android.foo/android.test.InstrumentationTestRunner

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

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

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

  完整的操作过程

  总结以上所有的内容,编写并运行完整的测试需要以下的步骤:

  以上步骤中,在 Android自带的例子中,我发现它有两个manifest.xml。也就是说在步骤3中源代码和测试代码分别生成了两个不同的包。然后步骤4利用 adb install命令安装到了虚拟机上。由于我没有找到Eclipse ADT有办法可以为一个只有Instrumentation,没有Activity的Application打包并安装,于是采用了略微不同的办法完成了这个工作。下文中将一一详细介绍整个过程。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。