开发中我们需要对部分功能进行单元测试,启动Activity来测试部分小功能,有点小题大作,杀鸡用牛刀。

我们可以用Android单元测试 Instrumentation

本篇只是入门,起到抛砖的效果

Instrumentation无界面,具有启动能力。

下面通过一个简单的例子来讲解Instrumentation的基本测试方法:

我们测试工程

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.hpc.assistant"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:name=".FloatApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" android:debuggable="true">
<activity
android:name="cn.hpc.assistant.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner" /><!--八股文:  引入测试库-->
</application>
<!--  八股文:被测试的目标包与instrumentation的名称。-->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:label="Tests for My App"
android:targetPackage="cn.hpc.assistant" />
</manifest>

Mainactivity.java

package cn.hpc.assistant;import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;public class MainActivity extends Activity {private TextView tv = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) this.findViewById(R.id.text1);this.findViewById(R.id.id_btn_fun).setOnClickListener(mOnClickListener);}View.OnClickListener mOnClickListener = new View.OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.id_btn_fun:fun();break;default:}}};private void fun(){tv.setText(android.os.Build.MODEL + android.os.Build.getRadioVersion());}}

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"tools:context=".MainActivity" ><TextViewandroid:id="@+id/text1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="@string/hello_world" /><Buttonandroid:id="@+id/id_btn_fun"android:layout_width="wrap_content"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/id_btn_day"android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="Day"/><Buttonandroid:id="@+id/id_btn_night"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Night" /></LinearLayout>

键的测试文件:

package cn.hpc.assistant.test;import junit.framework.Assert;
import android.content.Intent;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.widget.Button;
import android.widget.TextView;
import cn.hpc.assistant.MainActivity;
import cn.hpc.assistant.R;public class TestMyApp extends InstrumentationTestCase {MainActivity mActivity = null;private Button button = null;private TextView text = null;public void testSample() throws Throwable {Assert.assertTrue(1 + 1 == 3); // 测试一个错误的结果}@Overrideprotected void tearDown() throws Exception {// TODO Auto-generated method stubmActivity.finish();super.tearDown();}@Overrideprotected void setUp() throws Exception {// TODO Auto-generated method stubsuper.setUp();Intent intent = new Intent();intent.setClassName("cn.hpc.assistant", MainActivity.class.getName());intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);mActivity = (MainActivity) getInstrumentation().startActivitySync(intent);text = (TextView) mActivity.findViewById(R.id.text1);button = (Button) mActivity.findViewById(R.id.id_btn_fun);}/** * 活动功能测试*/public void testActivity() throws Exception {// 测试键壮性,连续运行某项功能100次,点击Button 100次for (int i = 0; i < 100; ++i) {getInstrumentation().runOnMainSync(new PerformClick(button));SystemClock.sleep(500); // 中间间隔 0.5秒}assertEquals("Android InstrumentationTestCase", text.getText().toString()); //检查运行后的输出结果}/** * 模拟按钮点击的接口*/private class PerformClick implements Runnable {Button btn;public PerformClick(Button button) {btn = button;}public void run() {btn.performClick();}}}

在android Developer中有如下的解释

protected void setUp ()
Since: API Level 3
Sets up the fixture, for example, open a network connection. This method is called before a test is executed.

setUp ()用来初始设置,如启动一个Activity,初始化资源等。

protected void tearDown ()
Since: API Level 3
Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.

tearDown () 用来垃圾清理与资源回收。

这个测试方法中,模拟了一个按钮点击事件,检查程序运行是否预期的结果。

在这里PerformClick这个方法引入Runnable接口,通过线程来执行模拟事件。这样的好处,不阻滞UI线程。

用Eclipse集成的JUnit工具启动测试

在Eclipse中选择工程Sample,单击右键,在Run as子菜单选项中选择Android JUnit Test

测试后,显示测试中的错误信息,

完毕,

欢迎转载,转载请注明出处。谢谢!

http://blog.csdn.net/hpccn/article/details/8439784

Android单元测试 Instrumentation相关推荐

  1. Android单元测试全解

      自动化测试麻烦吗?说实在,麻烦!有一定的学习成本.但是,自动化测试有以下优点: 节省时间:可以指定测试某一个activity,不需要一个个自己点 单元测试:既然Java可以进行单元测试,Andro ...

  2. 单元测试instrumentation入门---eclipse

    前言:进公司要先做两个月测试,我了个去,对测试是不大了解啊,在测试主管的指导下学instrumentation接口,好像还挺好用的,看到一篇文章将其稍做补充摘录于下,分享给大家. 参考文章地址:< ...

  3. android单元测试android环境,基于Robolectric的Android单元测试 —环境搭建与部署运行...

    移动端的测试中,因为回归一些逻辑分支比较多的功能时工作量比较大,且不太适合用UI完成,尝试通过单元测试来完成.几经波折终于完成了一个功能的UT用例并在CI上部署运行,现总结如下: 一.Robolect ...

  4. android单元测试AndroidTestCase

    在实际开发中,开发android软件的过程需要不断的进行测试.而是用Junit测试框架,则是正规android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性. 第一 ...

  5. (转)Android单元测试

    关键字: camera unit test android源代码中每个app下中都自带了一个test用例,下面主要介绍下camra单元测试用例 在AndroidManifest.xml中标明了测试用例 ...

  6. Android单元测试思路

    如果想在android里面做单元测试,有两条基本的路子可行. 第一, 就是java程序员最为熟悉和常用的JUnit, 但是由于目前android sdk (version 1.1)中只是提供了stub ...

  7. android单元测试demo,android单元测试AndroidTestCase

    在实际开发中,开发android软件的过程需要不断的进行测试.而是用Junit测试框架,则是正规android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性. 比如 ...

  8. android测试入门选择哪个工具何时,Android单元测试——辅助工具介绍

    8种机械键盘轴体对比 本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选? 阅读本文大约需要8分钟 目录 最近在学习单元测试的相关知识,在这里我将分享一下我在学习过程中,使用到的一些辅助工具或框架 ...

  9. Android测试最新框架,Android单元测试-常见的方案比较

    前言 本文将介绍在Android Studio中,android单元测试的介绍和实现.相关代码托管在github上的AndroidJunitDemo中,涉及到的用例代码收集于google官方提供的测试 ...

最新文章

  1. python之内置函数
  2. JPA(七):映射关联关系------映射双向多对一的关联关系
  3. Silverlight测试——利用Ranorex实现数据驱动测试
  4. avrstudio5 拨码管
  5. 记录一下自动白平衡与自动亮度
  6. 安卓Activity界面切换添加动画特效
  7. 汇编中数据处理的基本问题
  8. 一文教你玩转链上「动森」My Neighbor Alice
  9. SAP Spartacus Customizing CMS Components
  10. Navicat Premium连接SQL Server
  11. 华为又对计算机视觉下手了!
  12. OSPF笔记——LSA及其字段,及其作用
  13. Pytorch CUDA GPU运算模型训练缓慢的一个可能原因
  14. iOS 处理后台返回的json(或NSDictionary)形式字符串
  15. Anaconda 安装 OpenCV 遇到的问题
  16. 小脚丫 LCMXO2 4000HC FPGA入门——点个灯
  17. 大数据服务器环境准备(三台服务)
  18. 天边一朵云-徒手用html生成一朵云,很真的那种
  19. jenkins 运行 jenkins-agent.jnlp 报错None of the protocols are enabled
  20. 南京邮电大学C语言实验报告一

热门文章

  1. 阿里云官方学习课程推荐-Linux运维学习路线 从事云计算运维相关工作必备技能
  2. 服务异步通信RabbitMQ
  3. 复杂交通流对混合交通的影响研究多向车流量分析
  4. 【python】Flask
  5. Swift 标准库源码 第三方,Almofire,Kingfisher,SwiftyJson,KakaJson,单元测试 request
  6. BCB操作EXCEL
  7. 基于html+js实现轮播图(自动轮播、左右按钮、小圆点点击及切换图片)
  8. forward 和 redirect
  9. Object 的 equal() 、hashCode()方法说起
  10. 全国各区县经纬度查询困难?精度不够?试试自制市区县经纬度查询工具并将数据保存本地