(转)robotium脚本封装为APK,实现脱离手机数据线,使用按钮点击控制用例运行

原文:http://blog.sina.com.cn/s/blog_5b478f870102v9my.html


最近一直在完成一些robotium的小功能,用来更方便的完成一些小功能的测试,或者可以说用来娱乐吧,幸得群内大神思路指点,就此引申,终于把这个功能得以实现

---------------将robotium脚本封装为APK,使用按钮控制用例运行覆盖程度,测试结果以简单的xml文件输入到手机SD卡目录下----------------------

废话不多说,转正题:

一、首先明确一点,这篇文章,是在你所编写的robotium脚本运行无异常的前提下实施

二、阐明思路:

   1.我们需要一个运行良好的,逻辑正常的robotium工程

   2.我们需要一个可以将脚本用例运行结果保存至本地的方法

   3.我们需要一个activity,一个按钮,以及一个按钮点击事件去运行我们的robotium脚本

 

三、先介绍脚本用例运行结果的功能,我们都知道robotium用例的运行是依赖junit的Instrumentation的,所以,关于结果的输出,需要我们重写InstrumentationTestRunner类

 

package baih;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;


public class InstrumentationTestRunner extends android.test.InstrumentationTestRunner {
    private Writer mWriter;
    private XmlSerializer mTestSuiteSerializer;
    private long mTestStarted;
    private static final String JUNIT_XML_FILE = "TEST-all.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, "testsuites");
            mTestSuiteSerializer.startTag(null, "testsuite");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
   
   
    private boolean isSDCardAvaliable(){
        return Environment.getExternalStorageState()
                    .equals(Environment.MEDIA_MOUNTED);   
    }
   
   
    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;
          

你可能感兴趣的:(转帖备忘)