android自动化测试之生成单元测试报告

本文介绍了如何在Android中进行自动化测试,并生成单元测试报告。首先,展示了原始代码,然后提供了代码优化方案。通过在Eclipse中配置JUnit运行配置,选择自定义的`SampleTestResult`类作为`InstrumentationTestRunner`。运行测试后,可以在手机SD卡中找到测试结果文件,以便进一步分析。此外,为了运行多个测试类,文章建议创建一个`TestSuite`类来整合各个测试用例。

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

原文来自:http://blog.youkuaiyun.com/hunterno4/article/details/14485663

并补充对改代码的优化

代码部分


public class SampleTestResult extends InstrumentationTestRunner {
	private static final String JUNIT_XML_FILE = "TEST-all.xml";
	private XmlSerializer mTestSuiteSerializer;
	private Writer mWriter;
	private long mTestStarted;

	@Override
	public TestSuite getAllTests() {
		return new TestSuite();
	}

	/***
	 * 开始测试时调用此方法
	 */
	@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();
	}

	/**
	 * 创建写文件流内容
	 * 
	 * @param writer
	 */
	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);
		}
	}

	/**
	 * 获取测试结果报告文件所在的路径
	 * 
	 * @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;
	}

	/***
	 * 创建写文件方法
	 * 
	 * @param writer
	 * @return
	 */

	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);
		}
	}

	/**
	 * 判断SD卡是否存在
	 * 
	 * @return
	 */
	private boolean isSDCardAvaliable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	@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;
		}
	}

	/***
	 * 开始测试时间
	 * 
	 * @param results
	 */
	void recordTestStart(Bundle results) {

		mTestStarted = System.currentTimeMillis();
	}

	/***
	 * 测试结果存放如xml样式
	 * 
	 * @param resultCode
	 * @param results
	 *            测试结果传过来的数据
	 * @throws IOException
	 */
	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);
		}
	}
}

2.在Androidmainfest.xml文件中需要进行修改:

原来代码显示为:

  <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.被测app包名.cn" />
修改后的代码显示为:

<instrumentation        android:name="com.targtime.mtll.testResult.SampleTestResult"

        android:targetPackage="com.被测app包名.cn" />

3.编写完成后,需要在eclipse中右键运行时选择“run configurations”-junit-中的需要运行的测试类名,并在test中设置“run时选用的

InstrumentationTestRunner为最新创建的“SampleTestResult类”

4.运行后进入手机SD卡中超找文件,并导出本地结果进行查看

补充:

5.因为多个类可以需要同时运行,所以需要建立一个“TestSuite”类

public class SampleTestSuite extends TestSuite {
	public static Test suite() {
		TestSuite ts = new TestSuite();
		ts.addTestSuite(Test1.class);
		ts.addTestSuite(Test2.class);
		return ts;
	}
}
直接运行此类所有测试类的结果都在文件中生成



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值