---
title: "android-junit单元测试(附代码)"
author: "15035554141"
date: "2014-07-19T11:25:27Z"
tags: []
categories: ["移动开发"]
slug: "android-junit"
draft: false
lastmod: "2014-07-19T11:29:04Z"
id: 2093930
url: "https://15035554141.iteye.com/blog/2093930"
---

**Android-junit 单元测试：**

 

一个好的软件不是写出来的是测出来的，接下来手工引入 junit 框架

为你的application 做单元测试，使它更强壮吧！

 

首先创建工程，我们需要一个service 类进行测试  待测试的 service方法

 

Java 代码：

```
package com.liwei.junittest.services;

/**
 * 业务方法，junit 测试用 
 * 
 * @author liwei
 * 
 */
public class CalcService {
	public int add(int x, int y) {
		return x + y;
	}
	public static void main(String[] args) {
		System.out.println("1111");
	}
	/**
	 * Invalid layout of java.lang.String at value # # A fatal error has been
	 * detected by the Java Runtime Environment: # # Internal Error
	 * (javaClasses.cpp:129), pid=19356, tid=19740 # fatal error: Invalid layout
	 * of preloaded class # # JRE version: 7.0_25-b17 # Java VM: Java
	 * HotSpot(TM) 64-Bit Server VM (23.25-b01 mixed mode windows-amd64
	 * compressed oops) # Failed to write core dump. Minidumps are not enabled
	 * by default on client versions of Windows # # An error report file with
	 * more information is saved as: #
	 * D:\android_code\junittest\hs_err_pid19356.log # # If you would like to
	 * submit a bug report, please visit: #
* 右击直接运行，发生错误
	 * http://bugreport.sun.com/bugreport/crash.jsp # 安装到虚拟机时错误， log
	 * 保存到D:\android_code\junittest\hs_err_pid19356.log 如果你想上传 bug
	 * 请上传到http://bugreport.sun.com/bugreport/crash.jsp # 
	 * 原因：右键运行，不能直接运行在java虚拟机中
	 * android-运行 首先打包apk 上传到手机， 运行在 手机dvk 虚拟机中 
	 */
}
```

 

创建一个 测试方法  extends AndroidTestCase

代码：

```
package com.liwei.junittest.test;

import com.liwei.junittest.services.CalcService;

import android.test.AndroidTestCase;

public class TestCalcService extends AndroidTestCase {

	/**
	 * add 方法的测试代码 把异常抛给测试框架
	 * 
	 * @throws Exception
	 */
	public void testAdd() throws Exception {
		CalcService service = new CalcService();
		int result = service.add(3, 5);
		assertEquals(8, result);// 断言是否为正确结果
	}
}


```

 

引入框架需要 引入 函数库  和指令集

指令集

```
<instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.liwei.junittest" >
    </instrumentation>
```

函数库在application 节点下 引入

```
<uses-library android:name="android.test.runner"/>
```

 

接下来进行测试，右击 Run As Android JUnit Test 以 Android JUnit 运行

[android-run\_as\_junit.png](http://dl2.iteye.com/upload/attachment/0099/3327/c592278e-4e71-3484-a626-bfe00771f3de.png)

junit 运行流程

[android-result.png](http://dl2.iteye.com/upload/attachment/0099/3329/e4eb998a-b571-3b29-a68e-ae2797fc9eb7.png)

首先 检查 android虚拟机是否启动

Adb  是否连接

执行 指令集

 

然后把junit 的apk装到 虚拟机上 成功后

执行指令集， 发送测试信息

 

期待值失败

 

[android-jfail.png](http://dl2.iteye.com/upload/attachment/0099/3333/5b8e569a-b4c0-3c80-bee1-d010369f0450.png)