`
dowhathowtodo
  • 浏览: 775071 次
文章分类
社区版块
存档分类
最新评论

android基础知识12:android自动化测试06—Instrumentation 01 例子

 
阅读更多
下面通过一个简单的例子来讲解Instrumentation的基本测试方法。在这个例子中我们会建立一个简单的android应用,同时在其上添加Instrumentation测试程序。

1.首先建立一个android project,其文件结构最终如下:


2、布局文件

<?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>
3、被测程序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.同时,在这个类中,我还写了一个简单的方法,没有被调用,仅供测试而已。
4、测试类SampleTest
通常可以将测试程序作为另一个android应用程序。但是这里我们为了操作方便,写在了一个应用里面了。
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线程。
<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的测试内容还有很多,也有比较复杂的,我会在以后的学习过程中继续分享我的体会。好了,今天就到这里吧!


参考资料:

Android单元测试初探——Instrumentation

分享到:
评论

相关推荐

    Android单元测试初探——Instrumentation

    学习Android有一段时间了,虽然前段时间对软件测试有了一些了解,不过接触android的单元测试却是头一次。这几天在物流大赛上也用了不少时间,所以对于android的单元测试没有太深入的研究,所以先写个基本入门吧!...

    Android UiAutomator 自动化测试

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

    源码

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

    android-support-multidex-instrumentation.jar.zip

    android-support-multidex-instrumentation.jar.zip

    Android自动化测试

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

    翻译:Valgrind: A Framework for Heavyweight Dynamic Binary Instrumentation

    学习valgrind必看的一篇论文-Valgrind: A Framework for Heavyweight Dynamic Binary Instrumentation,论文较长,这里是全文翻译。

    Android中Hook Instrumentation 的实现

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

    Android系统自动化测试简述

     Android自动化测试目前可借鉴的经验不多,现在采取的方式就是通过java代码对Activity和View进行操作,目前已知的入口是Instrumentation类。  Instrumentation与Activity均位于android.app包下,这个包内还有诸如...

    android自动化测试框架robotium的jar包、doc文档及source code

    著名的android自动化测试框架robotium出了4.1版本 在原有基础上增加了对webview的支持 方便好用,但是需要测试者有一定java开发基础 对android instrumentation有一定了解

    Android系统的自动化测试解决方案

    现在,已经有大量的Android自动化测试架构或工具可供我们使用,其中包括:ActivityInstrumentation,MonkeyRunner,Robotium,以及Robolectric。另外LessPainful也提供服务来进行真实设备上的自动化测试。  Android...

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

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

    android-support-multidex-instrumentation.jar

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

    安卓自动化测试框架

    通过android的instrumentation机制联系起来,可以用来对应用程序进行功能测试和简单的性能测试,测试程度也可以是从代码级别到具体功能点级别,到简单的性能测试级别。本文将从以下几个方面来对基于android平台的...

    详解Android单元测试最佳实践

    目的 ...这种方式运行速度快,对运行环境没有特殊要求,可以很方便的做自动化测试,是单元测试首选的方法 Instrumentation测试 Instrumentation测试需要运行在Android环境下,可以是模拟器或者手机等

    android 学习笔记

    电话拨号 使用系统自带意图对象完成: Intent intent=new Intent();... &lt;instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.xiaoqiang" /&gt; &lt;/manifest&gt;

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

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

    RESTMock:适用于Android Instrumentation测试的HTTP Server

    文章目录设置这是为Android设置RESTMock的基本规则步骤1:存储库将其添加到存储库末尾的root build.gradle中: allprojects {repositories {.. .maven { url " https://jitpack.io " }}}步骤2:依存关系添加依赖项...

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

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

    fastlane-plugin-aws_device_farm:此插件允许XCUITests和android Instrumentation测试在AWS设备场上运行

    适用于Fastlane的AWS设备场插件关于该插件允许测试在AWS设备场上运行的iOS 安卓失败设置添加插件fastlane add_plugin aws_device_farm创建设备池打开您的AWS仪表板,然后在AWS-Device Farm -配置您的设备池。...

Global site tag (gtag.js) - Google Analytics