`
isiqi
  • 浏览: 16028739 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论
阅读更多

关键字: camera unit test

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

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

Java代码
  1. <?xmlversion="1.0" encoding="utf-8" ?>
  2. <!--Copyright(C)2008 TheAndroidOpenSourceProject
  3. LicensedundertheApacheLicense,Version2.0 (the"License" );
  4. youmaynotusethis fileexceptincompliancewiththeLicense.
  5. YoumayobtainacopyoftheLicenseat
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  8. distributedundertheLicenseisdistributedonan"ASIS" BASIS,
  9. WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  10. SeetheLicensefor thespecificlanguagegoverningpermissionsand
  11. limitationsundertheLicense.
  12. -->
  13. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  14. package ="com.android.camera.tests" >
  15. <application>
  16. <uses-libraryandroid:name="android.test.runner" />
  17. </application>
  18. <instrumentationandroid:name="CameraLaunchPerformance"
  19. android:targetPackage="com.android.camera"
  20. android:label="CameraLaunchPerformance" >
  21. </instrumentation>
  22. <instrumentationandroid:name="com.android.camera.CameraStressTestRunner"
  23. android:targetPackage="com.android.camera"
  24. android:label="CameraStressTestInstrumentationRunner" >
  25. </instrumentation>
  26. <instrumentationandroid:name="android.test.InstrumentationTestRunner"
  27. android:targetPackage="com.android.camera"
  28. android:label="TestsforCameraapplication." />
  29. </manifest>



camera启动性能测试

Java代码
  1. package com.android.camera;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.test.LaunchPerformanceBase;
  5. /**
  6. *InstrumentationclassforCameralaunchperformancetesting.
  7. */
  8. public class CameraLaunchPerformanceextends LaunchPerformanceBase{
  9. public static final StringLOG_TAG="CameraLaunchPerformance" ;
  10. public CameraLaunchPerformance(){
  11. super ();
  12. }
  13. @Override
  14. public void onCreate(Bundlearguments){
  15. super .onCreate(arguments);
  16. mIntent.setClassName(getTargetContext(),"com.android.camera.Camera" );
  17. start();
  18. }
  19. /**
  20. *CallsLaunchAppandfinish.
  21. */
  22. @Override
  23. public void onStart(){
  24. super .onStart();
  25. LaunchApp();
  26. finish(Activity.RESULT_OK,mResults);
  27. }
  28. }



camera拍照压力测试,参数设定为反复拍照100次

Java代码
  1. package com.android.camera.stress;
  2. import com.android.camera.Camera;
  3. import android.app.Instrumentation;
  4. import android.test.ActivityInstrumentationTestCase2;
  5. import android.test.suitebuilder.annotation.LargeTest;
  6. import android.util.Log;
  7. import android.view.KeyEvent;
  8. /**
  9. *Junit/Instrumentationtestcaseforcameratest
  10. *
  11. *Runningthetestsuite:
  12. *
  13. *adbshellaminstrument\
  14. *-eclasscom.android.camera.stress.ImageCapture\
  15. *-wcom.android.camera.tests/com.android.camera.CameraStressTestRunner
  16. *
  17. */
  18. public class ImageCaptureextends ActivityInstrumentationTestCase2<Camera>{
  19. private StringTAG="ImageCapture" ;
  20. private static final int TOTAL_NUMBER_OF_IMAGECAPTURE=100 ;
  21. private static final int TOTAL_NUMBER_OF_VIDEOCAPTURE=100 ;
  22. private static final long WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN=1000 ;
  23. private static final long WAIT_FOR_VIDEO_CAPTURE_TO_BE_TAKEN=50000 ;//50seconds
  24. private static final long WAIT_FOR_PREVIEW=1000 ;//1seconds
  25. public ImageCapture(){
  26. super ("com.android.camera" ,Camera.class );
  27. }
  28. @Override
  29. protected void setUp()throws Exception{
  30. getActivity();
  31. super .setUp();
  32. }
  33. @Override
  34. protected void tearDown()throws Exception{
  35. super .tearDown();
  36. }
  37. @LargeTest
  38. public void testImageCapture(){
  39. Instrumentationinst=getInstrumentation();
  40. try {
  41. for (int i=0 ;i<TOTAL_NUMBER_OF_IMAGECAPTURE;i++){
  42. Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
  43. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
  44. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
  45. Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
  46. }
  47. }catch (Exceptione){
  48. Log.v(TAG,e.toString());
  49. }
  50. assertTrue("testImageCapture" ,true );
  51. }
  52. @LargeTest
  53. public void testVideoCapture(){
  54. Instrumentationinst=getInstrumentation();
  55. //Switchtothevideomode
  56. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
  57. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
  58. try {
  59. for (int i=0 ;i<TOTAL_NUMBER_OF_VIDEOCAPTURE;i++){
  60. Thread.sleep(WAIT_FOR_PREVIEW);
  61. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
  62. //recordanvideo
  63. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
  64. Thread.sleep(WAIT_FOR_VIDEO_CAPTURE_TO_BE_TAKEN);
  65. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
  66. Thread.sleep(WAIT_FOR_PREVIEW);
  67. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
  68. }
  69. }catch (Exceptione){
  70. Log.v(TAG,e.toString());
  71. }
  72. assertTrue("testVideoCapture" ,true );
  73. }
  74. }



camera拍照视频录制切换测试

Java代码
  1. package com.android.camera.stress;
  2. import com.android.camera.VideoCamera;
  3. import android.app.Instrumentation;
  4. import android.test.ActivityInstrumentationTestCase2;
  5. import android.test.suitebuilder.annotation.LargeTest;
  6. import android.util.Log;
  7. import android.view.KeyEvent;
  8. /**
  9. *Junit/Instrumentationtestcaseforcameratest
  10. *
  11. *Runningthetestsuite:
  12. *
  13. *adbshellaminstrument\
  14. *-eclasscom.android.camera.stress.SwitchPreview\
  15. *-wcom.android.camera.tests/com.android.camera.CameraStressTestRunner
  16. *
  17. */
  18. public class SwitchPreviewextends ActivityInstrumentationTestCase2<VideoCamera>{
  19. private StringTAG="SwitchPreview" ;
  20. private static final int TOTAL_NUMBER_OF_SWITCHING=200 ;
  21. private static final long WAIT_FOR_PREVIEW=2000 ;
  22. public SwitchPreview(){
  23. super ("com.android.camera" ,VideoCamera.class );
  24. }
  25. @Override
  26. protected void setUp()throws Exception{
  27. getActivity();
  28. super .setUp();
  29. }
  30. @Override
  31. protected void tearDown()throws Exception{
  32. getActivity().finish();
  33. super .tearDown();
  34. }
  35. @LargeTest
  36. public void testSwitchMode(){
  37. //Switchingthevideoandthevideorecordermode
  38. Instrumentationinst=getInstrumentation();
  39. try {
  40. for (int i=0 ;i<TOTAL_NUMBER_OF_SWITCHING;i++){
  41. Thread.sleep(WAIT_FOR_PREVIEW);
  42. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
  43. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_LEFT);
  44. inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
  45. Thread.sleep(WAIT_FOR_PREVIEW);
  46. }
  47. }catch (Exceptione){
  48. Log.v(TAG,e.toString());
  49. }
  50. assertTrue("testSwitchMode" ,true );
  51. }
  52. }





如果想在android里面做单元测试,有两条基本的路子可行。

  第一, 就是java程序员最为熟悉和常用的JUnit, 但是由于目前android sdk (version 1.1)中只是提供了stubbed methods/classes,没有具体的实现代码,所以如果用JUnit的话,我们需要在运行单元测试时,一定要用JDK来运行,利用java命令来 启动JUnit的某个Runner。如果是用Eclipse的话,可以在Run Configuration里新建一个JUnit。但是一定要记得在Classpath选项卡里将Bootstrap Entries中的Android Library改成JRE,并且添加junit.jar。具体的设置可以参考:http://developer.android.com/guide /appendix/faq/troubleshooting.html#addjunit。而且,更为遗憾的是,这种方法运行的JUnit运行在JDK 之上的,而不是android,所以,只能测试一些和android无关的东西,比如业务逻辑,数据封装,数值计算等等。并不能测试android api。

  第二, 采用Instrumentation. Android单元测试的主入口是InstrumentationTestRunner。它相当于JUnit当中TestRunner的作用。你可以将 Instrumentation理解为一种没有图形界面的,具有启动能力的,用于监控其他类(用Target Package声明)的工具类。任何想成为Instrumentation的类必须继承android.app.Instrumentation。

  下面通过一个实例来看一下如何通过Instrumentation来做单元测试。

  Step 1.首先编写需要测试的activity:

Java代码
  1. import android.app.Activity;
  2. import android.os.Bundle;
  3. public class AndroidUTextends Activity{
  4. /**Calledwhentheactivityisfirstcreated.*/
  5. @Override
  6. public void onCreate(BundlesavedInstanceState){
  7. super .onCreate(savedInstanceState);
  8. setContentView(R.layout.main);
  9. }
  10. public int add(int a,int b)
  11. {
  12. return a+b;
  13. }
  14. }



  Step 2.

  接下来编写测试类,其中主要来测试add()方法。我们在当前代码目录下,在新建一个文件夹,命名为test,并在里面新建了包com.android.ut.test。然后往里面新增加一个class.具体如下:

Java代码
  1. import com.android.ut.AndroidUT;
  2. import android.test.ActivityInstrumentationTestCase;
  3. public class TestAppextends ActivityInstrumentationTestCase<AndroidUT>{
  4. public TestApp()
  5. {
  6. super ("com.android.ut" ,AndroidUT.class );
  7. }
  8. public void testSum()
  9. {
  10. assertEquals(5 ,getActivity().add(2 ,3 ));
  11. }
  12. }


  Step 3.最后一步就是要改一下Manifest文件。

Java代码
  1. <?xmlversion="1.0" encoding="utf-8" ?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package ="com.android.ut"
  4. android:versionCode="1"
  5. android:versionName="1.0.0" >
  6. <applicationandroid:icon="@drawable/icon" android:label="@string/app_name" >
  7. <activityandroid:name=".AndroidUT"
  8. android:label="@string/app_name" >
  9. <intent-filter>
  10. <actionandroid:name="android.intent.action.MAIN" />
  11. <categoryandroid:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. </activity>
  14. <uses-libraryandroid:name="android.test.runner" />
  15. </application>
  16. <instrumentationandroid:targetPackage="com.android.ut" android:name="android.test.InstrumentationTestRunner" android:label="TestUnitTests" ></instrumentation>
  17. </manifest>


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

  

Java代码
  1. <uses-libraryandroid:name="android.test.runner" />



  以及:

  

Java代码
  1. <instrumentationandroid:targetPackage="com.android.ut" android:name="android.test.InstrumentationTestRunner" android:label="TestUnitTests" ></instrumentation>


  Step 4.运行

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

Java代码
  1. adbshellaminstrument-eclass com.android.ut.test.TestApp-wcom.android.ut/android.test.InstrumentationTestRunner



  这样你就可以看到测试结果了。

Java代码
  1. #aminstrument-eclass com.cn.test.TestApp-wcom.cn/android.test.InstrumentationTestRunner
  2. com.cn.test.TestApp:..
  3. Testresultsfor InstrumentationTestRunner=..
  4. Time:2.866
  5. OK(2 tests)



后台测试log日志信息

Java代码
  1. D/AndroidRuntime(941 ):>>>>>>>>>>>>>>AndroidRuntimeSTART<<<<<<<<<<<<<<
  2. D/AndroidRuntime(941 ):CheckJNIisON
  3. D/AndroidRuntime(941 ):---registeringnative functions---
  4. D/FileBackupHelper_native(941 ):register_android_backup_FileBackupHelper
  5. D/ActivityManager(581 ):Uninstallingprocesscom.cn
  6. I/ActivityManager(581 ):Startproccom.cnfor addedapplicationcom.cn:pid=948 uid=10013 gids={}
  7. I/TestRunner(948 ):started:testSum(com.cn.test.TestApp)//启动add()测试方法
  8. I/ActivityManager(581 ):Startingactivity:Intent{act=android.intent.action.MAINflg=0x10000000 cmp=com.cn/.AndroidUT}
  9. I/ActivityManager(581 ):Displayedactivitycom.cn/.AndroidUT:645 ms(total645 ms)
  10. I/TestRunner(948 ):finished:testSum(com.cn.test.TestApp)
  11. I/TestRunner(948 ):passed:testSum(com.cn.test.TestApp)
  12. I/TestRunner(948 ):started:testActivityTestCaseSetUpProperly(com.cn.test.TestApp)
  13. I/ActivityManager(581 ):Startingactivity:Intent{act=android.intent.action.MAINflg=0x10000000 cmp=com.cn/.AndroidUT}
  14. I/ActivityManager(581 ):Displayedactivitycom.cn/.AndroidUT:412 ms(total412 ms)
  15. I/TestRunner(948 ):finished:testActivityTestCaseSetUpProperly(com.cn.test.TestApp)
  16. I/TestRunner(948 ):passed:testActivityTestCaseSetUpProperly(com.cn.test.TestApp)
  17. D/ActivityManager(581 ):Uninstallingprocesscom.cn
  18. D/ActivityManager(581 ):ForceremovingprocessProcessRecord{43851fa0948 :com.cn/10013 }(com.cn/10013 )
  19. D/AndroidRuntime(941 ):ShuttingdownVM



(二) 转

任何程序的开发都离不开单元测试来保证其健壮和稳定。Android的程序自然也不例外。从Android SDK 0.9开始,就有了比较成熟的测试框架,但是直到目前最新的1.1版本,也没有详细的文档介绍这个内容,只是简单的给了一个Api Demos里的几个单元测试代码。因此,我在这里对此内容做一下梳理和总结: JUnit还能用么?

在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。


很明显的,这种测试就是正规的Java单元测试,和Android没有任何关系。你无法测试任何关于Android系统中的API,你写的 Activity,人机界面等等。所以,如果你想测试仅仅是一些封装数据的对象,或者是纯粹的数值计算,还是可以用这种方法的。 Android里面的junit.framework包是怎么回事?

很多人看到这个包的时候,第一反应是Android是不是已经完整集成了JUnit。很遗憾这不是事实。如果你按照JUnit的运行方法,却不像上面那样改用JDK,就一定会得到一个异常:

Java代码
  1. #
  2. #AnunexpectederrorhasbeendetectedbyJavaRuntimeEnvironment:
  3. #
  4. #InternalError(classFileParser.cpp:2924 ),pid=4900 ,tid=4476
  5. #Error:ShouldNotReachHere()
  6. #
  7. #JavaVM:JavaHotSpot(TM)ClientVM(10.0 -b19mixedmodewindows-x86)
  8. #Anerrorreportfilewithmoreinformationissavedas:
  9. #E:\Mydoc\EclipseWorkspace\TestAndroid\hs_err_pid4900.log
  10. #
  11. #Ifyouwouldliketosubmitabugreport,pleasevisit:
  12. #http://java.sun.com/webapps/bugreport/crash.jsp
  13. #



实际上,TestCase这个类用于在Android担当所有独特的TestCase的基类的作用,它是一个Abstract Class。Android单元测试类继承关系图如下所示:


之所以有那么多XXXTestCase主要是为了简化工作。例如当你想对一个访问数据库的功能进行测试时,首先需要自己启动并初始化数据库。在这 里是类似的,如果你想测试一个Activity,首先要启动它。而ActivityTestCase就会自动帮你做完这些事情。而 ActivityUnitTestCase会更注重测试的独立性,它会让测试与Android底层的联系降到最低。其余的类可以查看相关的Javadoc 来按需挑选。要编写测试,就是找到合适的XXXTestCase作为基类来继承,并且编写自己的测试方法。

很明显的,最简单的编写测试的方法就是继承AndroidTestCase写一个自己的TestCase。然后为自己的一组 TestCase写一个Activity界面,由界面控制TestCase的启动,运行和结果报告。但是,你很快会发现,为何要给测试写一个界面呢?这太 诡异了。这时就需要一种技术,它可以利用命令行(Shell)来启动一组测试,并且通过命令行的形式给出结果。这就是所谓的 Instrumentation。 什么是Instrumentation?

一般在开发Android程序的时候,需要写一个manifest文件,其结构是:

Java代码
  1. <applicationandroid:icon="@drawable/icon" android:label="@string/app_name" >
  2. <activityandroid:name=".TestApp" android:label="@string/app_name" >
  3. ……
  4. </activity>
  5. </application>



这样,在启动程序的时候就会先启动一个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代码
  1. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  2. package ="com.example.android.apis.tests" >
  3. <application>
  4. <uses-libraryandroid:name="android.test.runner" />
  5. </application>
  6. <instrumentationandroid:name="android.test.InstrumentationTestRunner"
  7. android:targetPackage="com.example.android.apis"
  8. android:label="TestsforApiDemos." />
  9. </manifest>



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


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

Java代码
  1. adbshellaminstrument–wXXXXXX



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

Java代码
  1. adbshellaminstrument-wcom.android.foo/android.test.InstrumentationTestRunner



当然,也可以利用adb shell先进入android命令行模式,再直接写am instrument –w XXXXXXX。下面将具体介绍如何将根据需要加载一组单元测试。 如何在Android中利用Instrumentation来进行测试?

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

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

Java代码
  1. adbshellaminstrument-wcom.android.foo/android.test.InstrumentationTestRunner


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

Java代码
  1. adbshellaminstrument-eclass com.android.foo.MyTestSuite-wcom.android.foo/android.test.InstrumentationTestRunner



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

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

Java代码
  1. adbshellaminstrument-eclass com.android.foo.MyTestCase-wcom.android.foo/android.test.InstrumentationTestRunner


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

相关推荐

Global site tag (gtag.js) - Google Analytics