robotium测试demo
- demo是独立app,demo和测试app同时安装到设备上。打开demo点击测试按钮,开始测试。脱离开发环境,测试报告将生成xml文件,通过webview加载到demo上。
- https://github.com/RobotiumTech/robotium 下载jar包 或者源码。此demo下载源码放入项目中,方便学习,查看。
- 安装 robotium recorder。官方网址http://robotium.myshopify.com/products/robotium-recorder 。eclipse安装 Help > Install New Software,add添加http://recorder.robotium.com/updates
- 新建项目。File > New > Other > Android - Robotium Recorder
- 看提示 选中要测试的app项目,点击Next > New Robotium Test,等app在设备或者虚拟机上跑起来后,就可以开始你的要测试的操作。完成后 Save > finish。Package Explorer里面会多处一个你的测试项目。先看下AndroidManifest.xml和 src下面自动生成的代码。下面将重写InstrumentationTestRunner 类,生成我们自己想要的xml文件。
- 新建在com.xxx.example类下新建InstrumentationTestRunner 继承 android.test.InstrumentationTestRunner。
public class InstrumentationTestRunner extends android.test.InstrumentationTestRunner { private Writer mWriter; private XmlSerializer mTestSuiteSerializer; private long mTestStarted; private static final String JUNIT_XML_FILE = "TEST-REPORT.xml"; @Override public void onStart() {try{ File fileRobo = new File(getTestResultDir(getTargetContext())); if(!fileRobo.exists()){ fileRobo.mkdir(); } if(isSDCardAvaliable()){ File resultFile = new File(getTestResultDir(getTargetContext()),JUNIT_XML_FILE); startJUnitOutput(new FileWriter(resultFile)); }else{ startJUnitOutput(new FileWriter(new File(getTargetContext().getFilesDir(), JUNIT_XML_FILE))); } } catch(IOException e){ throw new RuntimeException(e); } super.onStart(); } void startJUnitOutput(Writer writer) { try { mWriter = writer; mTestSuiteSerializer = newSerializer(mWriter); mTestSuiteSerializer.startDocument(null, null); mTestSuiteSerializer.startTag(null, Tag.SUITS); mTestSuiteSerializer.startTag(null, Tag.SUIT); } catch (Exception e) { throw new RuntimeException(e); } } /** * 判断SD卡是否存在 * @return */ private boolean isSDCardAvaliable(){ return Environment.getExternalStorageState() .equals(Environment.MEDIA_MOUNTED); } /** * 获取测试结果报告文件所在的路径 * @param context 被测工程的context * @return 返回测试结果报告文件所在的路径 */ private String getTestResultDir(Context context){ String packageName = "/" + "robotium"; String filepath = context.getCacheDir().getPath() + packageName; if(android.os.Build.VERSION.SDK_INT < 8){ if(isSDCardAvaliable()){ filepath = Environment.getExternalStorageDirectory().getAbsolutePath()+ packageName; } }else{ if(isSDCardAvaliable()){ filepath = Environment.getExternalStorageDirectory().getAbsolutePath()+ packageName; } }return filepath; } private XmlSerializer newSerializer(Writer writer) { try { XmlPullParserFactory pf = XmlPullParserFactory.newInstance(); XmlSerializer serializer = pf.newSerializer(); serializer.setOutput(writer); return serializer; } catch (Exception e) { throw new RuntimeException(e); } } @Override public void sendStatus(int resultCode, Bundle results) { super.sendStatus(resultCode, results); switch (resultCode) { case REPORT_VALUE_RESULT_ERROR: case REPORT_VALUE_RESULT_FAILURE: case REPORT_VALUE_RESULT_OK: try { recordTestResult(resultCode, results); } catch (IOException e) { throw new RuntimeException(e); } break; case REPORT_VALUE_RESULT_START: recordTestStart(results); default: break; } } void recordTestStart(Bundle results) { mTestStarted = System.currentTimeMillis(); }boolean isSuccess = true;void recordTestResult(int resultCode, Bundle results) throws IOException { float time = (System.currentTimeMillis() - mTestStarted) / 1000.0f; String className = results.getString(REPORT_KEY_NAME_CLASS); String testMethod = results.getString(REPORT_KEY_NAME_TEST); String stack = results.getString(REPORT_KEY_STACK); int current = results.getInt(REPORT_KEY_NUM_CURRENT); int total = results.getInt(REPORT_KEY_NUM_TOTAL); mTestSuiteSerializer.startTag(null, Tag.SUIT); mTestSuiteSerializer.attribute(null, "classname", className);mTestSuiteSerializer.attribute(null, "name", testMethod); if (resultCode != REPORT_VALUE_RESULT_OK) { isSuccess = false;mTestSuiteSerializer.startTag(null,Tag.REASON); if (stack != null) { String reason = stack.substring(0, stack.indexOf('\n')); String message = ""; int index = reason.indexOf(':'); if (index > -1) { message = reason.substring(index+1); reason = reason.substring(0, index); } mTestSuiteSerializer.attribute(null, "message", message); mTestSuiteSerializer.attribute(null, "type", reason); mTestSuiteSerializer.text(stack); } mTestSuiteSerializer.endTag(null, Tag.REASON); } else { mTestSuiteSerializer.attribute(null,Tag.TIME, String.format("%.3f", time)); } mTestSuiteSerializer.endTag(null, Tag.SUIT); if (current == total) { mTestSuiteSerializer.endTag(null, Tag.SUIT); mTestSuiteSerializer.startTag(null, "测试结果");if(isSuccess) { mTestSuiteSerializer.text("恭喜!测试通过!"); } else {mTestSuiteSerializer.text("Sorry!请查看具体错误!!");}mTestSuiteSerializer.endTag(null, "测试结果");mTestSuiteSerializer.flush(); } } @Override public void finish(int resultCode, Bundle results) { endTestSuites(); Intent intent = new Intent();intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setComponent(new ComponentName("com.xxx.example.test", "com.xxx.example.test.HomeActivity"));getTargetContext().startActivity(intent);super.finish(resultCode, results);} void endTestSuites() { try { mTestSuiteSerializer.endTag(null, Tag.SUITS); mTestSuiteSerializer.endDocument(); mTestSuiteSerializer.flush(); mWriter.flush(); mWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } }
}
注意finish时,我们重启了我们的测试app的HomeActivity。测试报告路径为:
Environment.getExternalStorageDirectory()+"/robotium/TEST-REPORT.xml"
7.新建app的HomeActivity 这里就添加一个Button,一个textView和webview. 在按钮的点击事件
Log.d("HomeActivity", "start button is onClicked!");
if(!startInstrumentation(new ComponentName(getPackageName(), getPackageName()+".InstrumentationTestRunner"), null, null)) {
result.setText("启动测试失败");
} else {result.setText("测试中...");try {
Thread.sleep(1000);} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();}HomeActivity.this.finish();
}
通过startInstrumenation来启动测试,启动成功退出当前activity.这里要把我们上面重写的InstrumentationTestRunner类放在getPackageName()下。
HomeActivity的OnResume里面加载测试报告的xml文件 webView.loadUrl(path)即可。
8.配置AndroidManifest.xml manifest下添加
<instrumentationandroid:name="com.xxx.example.test.InstrumentationTestRunner"android:targetPackage="com.xxx.example" />
application下正常配置HomeActivity额外添加 <uses-library android:name="android.test.runner" />
9.运行项目。以Android Application运行,点击测试按钮启动测试。测试完成后,返回测试app并加载测试结果。
大致就是这些过程。这只是demo,正的测试还要完善xml的格式,recorder自动生成的测试用例等。自己的项目中包含公司信息,就不贴出来分享了。有什么指点或疑问,欢迎留言交流......