`
manying
  • 浏览: 6846 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Android单元测试初探——Instrumentation

阅读更多

         这是我以前在和讯博客上写的一篇文章,现在就把它转发到这里来,原文地址:

       和讯博客:http://14957395.blog.hexun.com/57120862_a.html

       华中科技大学OPhone俱乐部:http://www.dian.org.cn/ophone/?p=162

       先,我们来了解一下android的测试类的层次结构:

 

      可以看出android中的测试方法主要AndroidTextCaseInstrumentationTextCase.在这篇文章中,我将介绍Instrumentation这种测试方法,那么什么是Instrumentation

 InstrumentationActivity有点类似,只不过Activity是需要一个界面的,而Instrumentation并不是这样的,我们可以将它理解为一种没有图形界面的,具有启动能力的,用于监控其他类(Target Package声明)的工具类。

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

    1.首先建立一个android  project,类名为Sample,代码如下:

package com.hustophone.sample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; 

public class Sample extends Activity {

    private TextView myText = null;
    private Button button = null; 

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        myText = (TextView) findViewById(R.id.text1);

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {
 

            @Override

            public void onClick(View arg0) {

                // TODO Auto-generated method stub

                myText.setText("Hello Android");

            }

        });

    } 

    public int add(int i, int j) {

        // TODO Auto-generated method stub

        return (i + j);

    }

}

       这个程序的功能比较简单,点击按钮之后,TextView的内容由Hello变为Hello Android.同时,在这个类中,我还写了一个简单的方法,没有被调用,仅供测试而已。

   2src文件夹中添加一个测试包,在测试包中添加一个测试类SampleTest

    测试类的代码如下:

package com.hustophone.sample.test;
import com.hustophone.sample.R;
import com.hustophone.sample.Sample;
import android.content.Intent;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView; 

public class SampleTest extends InstrumentationTestCase {

    private Sample sample = null;
    private Button button = null;
    private TextView text = null;

    /*

     * 初始设置
     *
     * @see junit.framework.TestCase#setUp()
     */

    @Override

    protected void setUp()  {

        try {
            super.setUp();
        } catch (Exception e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent intent = new Intent();
        intent.setClassName("com.hustophone.sample", Sample.class.getName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        sample = (Sample) getInstrumentation().startActivitySync(intent);
        text = (TextView) sample.findViewById(R.id.text1);
        button = (Button) sample.findViewById(R.id.button1);

    }

    /*

     * 垃圾清理与资源回收

     *
     * @see android.test.InstrumentationTestCase#tearDown()

     */

    @Override

    protected void tearDown()  {

        sample.finish();

        try {

            super.tearDown();

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

 

    /*

     * 活动功能测试

     */

public void testActivity() throws Exception {

Log.v("testActivity", "test the Activity");

        SystemClock.sleep(1500);

        getInstrumentation().runOnMainSync(new PerformClick(button));

        SystemClock.sleep(3000);

        assertEquals("Hello Android", text.getText().toString());

    } 

    /*

     * 模拟按钮点击的接口

     */

    private class PerformClick implements Runnable {

        Button btn; 

        public PerformClick(Button button) {

            btn = button;

        } 

        public void run() {

            btn.performClick();

        }

    } 

    /*

     * 测试类中的方法

     */

    public void testAdd() throws Exception{

        String tag = "testAdd";

        Log.v(tag, "test the method");

        int test = sample.add(1, 1);

        assertEquals(2, test);

    } 

}

   下面来简单讲解一下代码:

  setUp()tearDown()都是受保护的方法,通过继承可以覆写这些方法。

  在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.

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. 

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

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

 在testActivity()这个测试方法中,我模拟了一个按钮点击事件,然后来判断程序是否按照预期的执行。在这里PerformClick这个方法继承了Runnable接口,通过新的线程来执行模拟事件,之所以这么做,是因为如果直接在UI线程中运行可能会阻滞UI线程。 

   3.要想正确地执行测试,还需要修改AndroidManifest.xml这个文件.

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.hustophone.sample" android:versionCode="1"
	android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<!--用于引入测试库-->
		<uses-library android:name="android.test.runner" />
		<activity android:name=".Sample" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
	<uses-sdk android:minSdkVersion="3" />
	<!--表示被测试的目标包与instrumentation的名称。-->
	<instrumentation android:targetPackage="com.hustophone.sample"
		android:name="android.test.InstrumentationTestRunner" />
</manifest>

 

     注意:以上xml代码中的<span></span>是粘贴后发表产生的,我试了几次,都删不掉,有哪位大侠知道的话可以指点指点。

     其中红色标记部分是添加的。

<uses-library android:name="android.test.runner" />用于引入测试库

<instrumentation android:targetPackage="com.hustophone.sample"

       android:name="android.test.InstrumentationTestRunner" />

   表示被测试的目标包与instrumentation的名称。 

   经过以上步骤,下面可以开始测试了。测试方法也有以下几种,下面介绍两个常用的方法:

 (1) Eclipse集成的JUnit工具

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


     同时可以通过LogCat工具查看信息

 (2) 通过模拟器运行单元测试

     点击模拟器界面的Dev Tools菜单

      再点击Instrumentation选项,进入Instrumentation菜单

    这里有一个InstrumentationTestRunner,它是测试的入口,点击这个选项,就可以自动运行我们的测试代码。以下为运行结果:

按钮点击前

按钮点击后

至此,一个简单的测试过程结束了。当然,android的测试内容还有很多,也有比较复杂的,我会在以后的学习过程中继续分享我的体会。好了,今天就到这里吧!


 

 

 

 

0
10
分享到:
评论
1 楼 George_ghc 2012-02-08  
不错!现在正在学习instrumentation类!

相关推荐

    源码

    《AndroidStudio单元测试——instrumentation》对应源码,博客地址:http://blog.csdn.net/harvic880925/article/details/38060361

    详解Android单元测试最佳实践

    在Android原生应用开发中,存在两种单元测试:本地JVM测试和Instrumentation测试。本文仅介绍本地JVM测试 本地jvm的单元测试 这种方式运行速度快,对运行环境没有特殊要求,可以很方便的做自动化测试,是单元测试...

    android-support-multidex-instrumentation.jar.zip

    android-support-multidex-instrumentation.jar.zip

    如何对Android系统手机进行单元测试

    中加入:外面加入:MISSIONandroid:name="android.permission.RUN_INSTRUMENTATION"/&gt;android:label="Testformyapp"/编写单元测试代码:必须继承自AndroidTe如何对Android系统手机进行单元测试 如何进行Android单元...

    Android中Hook Instrumentation 的实现

    参考博客 【Android中Hook Instrumentation 的实现】 http://blog.csdn.net/u012341052/article/details/71191409

    单元测试instrumentation入门---源码

    博客《单元测试instrumentation入门》对应的源码,博客地址:http://blog.csdn.net/harvic880925/article/details/37924189

    android-support-multidex-instrumentation.jar

    android-support-multidex-instrumentation.jar android-support-multidex-instrumentation.jar

    Android UiAutomator 自动化测试

    Instrumentation是早期Google提供的Android自动化测试工具类 UiAutomator也是Android提供的自动化测试框架,基本上支持所有的Android事件操作 Espresso,Android Studio工程,以apk的形式执行测试 UiAutomator2,...

    Android系统单元测试方法

    android源代码中每个app下中都自带了一个test用例,下面主要介绍下camra单元测试用例 在AndroidManifest.xml中标明了测试用例instrumentation函数入口 Java代码  &lt;?xml ...

    Android自动化测试

    Android自动化测试,该jar包支持robotium测试,当然支持所有的继承Instrumentation类型的测试

    fladle:使用Flank轻松在Firebase测试实验室中扩展您的Android Instrumentation测试

    襟翼使用Flank轻松扩展Firebase测试实验室上的Android Instrumentation测试。文档位于

    Android手机测试的自动化测试工具

    Android自动化测试相对来说还是比较难,Instrumentation比较难以使用。下面和大家分享一个Android自动化测试工具Robotium。Robotium是一款测试AndroidApp的测试框架,它使得编写黑盒测试代码更加容易和稳定。通过...

    instrumentation

    Instrumentation可以把测试包和目标测试应用加载到同一个进程中运行。既然各个控件和测试代码都运行在同一个进程中了,测试代码当然就可以调用这些控件的方法了,同时修改和验证这些控件的一些数据

    android 学习笔记

    得到单元测试框架: &lt;manifest&gt; &lt;uses-library android:name="android.test.runner"/&gt; &lt;instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage=...

    android-junit-report-dev

    1、 在应用tests目录文件下新建一个libs文件夹,将android-junit-...10、在应用代码根目录下(与sonar-project.properties同目录下)执行sonar-scanner命令,则可以在sonar网站中得到相关代码的覆盖率和单元测试数。

    instrumentation_demo.7z

    使用instrumentation创建测试用例示例代码

    Iocomp.Instrumentation.WF40

    Iocomp.Instrumentation.WF40.Common.dll,Iocomp.Instrumentation.WF40.Pro Iocomp.WF40.OPC

    Java Instrumentation笔记

    Java Instrumentation笔记 Java SE 6新特性:Instrumentation,利用 Java 代码,即 java.lang.instrument 做动态 Instrumentation 是 Java SE 5 的新特性,它把 Java 的 instrument 功能从本地代码中解放出来,使之...

Global site tag (gtag.js) - Google Analytics