Android使用Robotium自动化测试junit生成单元测试结果报告

本文介绍如何使用junit-report包配置Android工程,以生成JUnit格式的测试报告。包括添加依赖、修改配置文件、运行测试及获取报告的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



junit-report包下载地址:https://github.com/jsankey/android-junit-report/downloads


1、添加测试包到被测工程的lib下,Build Path---Add to Build Path


2、修改android的AndroidManifest文件,将

    <instrumentation
        android:name="android.test.InstrumentationTestRunner" 

修改为

    <instrumentation
        android:name="com.zutubi.android.junitreport.JUnitReportTestRunner" 


3、修改执行参数右键工程:Run As---Run Configurations

下拉选择修改为com.zutubi.android.junitreport.JUnitReportTestRunner


4、1运行Android JUnit Test,跑完测试用例后会在被测工程的文件夹下的files文件夹中生成junit-report.xml文件(/data/data/被测包名/files/junit-report.xml

4、2如果不使用Android JUnit Test,则按如下方式运行,注意修改

adb shell am instrument -e class com.netease.mobile.autotest.testing.LoginTest#testLogin -w com.netease.mobile.autotest/com.zutubi.android.junitreport.JUnitReportTestRunner

    adb shell am instrument -e class com.netease.mobile.autotest.testing.LoginTest#testUnLogin -w com.netease.mobile.autotest/com.zutubi.android.junitreport.JUnitReportTestRunner


5、adb pull /data/data/(your app package name)/files/junit-report.xml e:/  


如果要修改结果保存地址,需要重写类InstrumentationTestRunner


package com.example.test.instrumentation;

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;

/**
 * This test runner creates a TEST-all.xml in the files directory of the application under test. The output is compatible with that of the junitreport ant task, the format
 * that is understood by Hudson. Currently this implementation does not implement the all aspects of the junitreport format, but enough for Hudson to parse the test results. 
 */
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);
        }
    }
    
    /**
	 * 判断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();
    }

    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, "testcase");
        mTestSuiteSerializer.attribute(null, "classname", className);
        mTestSuiteSerializer.attribute(null, "name", testMethod);
        
        if (resultCode != REPORT_VALUE_RESULT_OK) {
            mTestSuiteSerializer.startTag(null, "failure");
            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, "failure");
        } else {
            mTestSuiteSerializer.attribute(null, "time", String.format("%.3f", time));
        }
        mTestSuiteSerializer.endTag(null, "testcase");        
        if (current == total) {
            mTestSuiteSerializer.startTag(null, "system-out");
            mTestSuiteSerializer.endTag(null, "system-out");
            mTestSuiteSerializer.startTag(null, "system-err");
            mTestSuiteSerializer.endTag(null, "system-err");
            mTestSuiteSerializer.endTag(null, "testsuite");
            mTestSuiteSerializer.flush();
        }
    }

    @Override
    public void finish(int resultCode, Bundle results) {
        endTestSuites();
        super.finish(resultCode, results);
    }

    void endTestSuites() {
        try {
            mTestSuiteSerializer.endTag(null, "testsuites");
            mTestSuiteSerializer.endDocument();
            mTestSuiteSerializer.flush();
            mWriter.flush();
            mWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值