第九章 性能和压力测试
9.2 Android SDK性能测试
如果9.2节中,通过添加日志状态这种衡量函数响应时间的方法不适合你的项目,这里还有另一种得到应用性能结果的方法。
不幸的是,基于Android SDK的性能测试还是个半成品(写这本书的时候,最新的版本只是Android 2.3)。我们没有办法从Android SDK应用中直接获取性能测试结果,因为Android测试用例用到的类是隐藏在Android SDK里面的,只有系统程序可以获取到,哪些程序是系统程序呢?就是那些作为主编译或者系统图像的一部分应用。由于这种策略不适合SDK应用,因此我们在那个方向上不再深挖了,需要再寻找别的可用的方法。
9.2.1 启动性能测试
这些性能测试用例跟用来测试系统应用的功能用例写法类似。思路就是继承andriod.app.Instrumentation并扩展几个功能函数,提供性能截图功能,自动创建的框架能够满足其他性能测试的需求。由于本书篇幅有限,这里就展示一个简单的用例。
9.2.1.1 新建LaunchPerformanceBase 设备
第一步,需要扩展Instrumentation类,满足我们性能测试的工具需要。我们这里用了一个新的包,名叫com.example.aatg.tc.test.launchperf,以便组织好测试用例,如框9.3所示。
框9.3
package com.example.aatg.tc.test.launchperf; import android.app.Instrumentation; import android.content.Intent; import android.os.Bundle; import android.util.Log; /** * Base class for all launch performance Instrumentation classes. */ public class LaunchPerformanceBase extends Instrumentation { public static final String TAG = "LaunchPerformanceBase"; protected Bundle mResults; protected Intent mIntent; /** * Constructor. */ public LaunchPerformanceBase() { mResults = new Bundle(); mIntent = new Intent(Intent.ACTION_MAIN); mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); setAutomaticPerformanceSnapshots(); } /** * Launches intent {@link #mIntent}, and waits for idle before * returning. */ protected void LaunchApp() { startActivitySync(mIntent); waitForIdleSync(); } @Override public void finish(int resultCode, Bundle results) { Log.v(TAG, "Test reults = " + results); super.finish(resultCode, results); } } |
我们这里扩展了Instrumentation。构造函数初始化了两个字段:mResults和mIntent。在最后,我们调用setAutomaticPerformanceSnapshots()函数,这个函数是性能测试用例的关键。
LaunchApp()函数负责启动被测行为活动,然后等待返回结果。
Finish()函数是把输出结果打印在日志中,然后调用Instrumentation的finish()函数。
9.2.2 新建TemperatureConverterActivityLaunchPerformance类
这个类通过Intent对象调用TemperatureConverterActivity,然后通过LaunchPerformanceBase类来测试已经启动的活动的性能,提供基本测试设施,如框9.4所示。
框9.4
package com.example.aatg.tc.test.launchperf; import com.example.aatg.tc.TemperatureConverterActivity; import android.app.Activity; import android.os.Bundle; /** * Instrumentation class for {@link TemperatureConverterActivity} launch performance testing. */ public class TemperatureConverterActivityLaunchPerformance extends LaunchPerformanceBase { /** * Constructor. */ public TemperatureConverterActivityLaunchPerformance() { super(); } @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); mIntent.setClassName("com.example.aatg.tc", "com.example.aatg.tc.TemperatureConverterActivity"); start(); } /** * Calls LaunchApp and finish. */ @Override public void onStart() { super.onStart(); LaunchApp(); finish(Activity.RESULT_OK, mResults); } } |
这里,onCreate()会调用父类中的onCreate(),这是Android生命周期开始的要求。然后,设置好Intent对象,执行类名和包名。接下来,调用Instrumentation的一个方法,start(),这个方法会新建并启动一个新的线程来运行设备。这个新线程会调用onStart(),就在这里运行设备。接着,调用LaunchApp()和finish()函数。
本文选自《Android应用测试指南》第五章,本站经人民邮电出版社和作者的授权。
版权声明:51Testing软件测试网获人民邮电出版社和作者授权连载本书部分章节。
任何个人或单位未获得明确的书面许可,不得对本文内容复制、转载或进行镜像,否则将追究法律责任。