instrumentation

来源:互联网 发布:黑马python视频教程 编辑:程序博客网 时间:2024/05/22 05:15

1 官方描述

instrumentation can load both a test package and the application under test into the same process. Since the application components and their tests are in the same process, the tests can invoke methods in the components, and modify and examine fields in the components.

翻译过来

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

2 如何实现获取控件及操作控件

Android instrumentation是android系统里面的一套控制方法或者”钩子“。这些钩子可以在正常的生命周期(正常是由操作系统控制的)之外控制Android控件的运行,其实指的就是Instrumentation类提供的各种流程控制方法,下表展示了部分方法的对应关系

MethodControl by User(Instrumentation)Control by OSonCreatecallActivityOnCreateonCreateonDestroycallActivityOnDestroyonDestroyonStartcallActivityOnStartonStart

具体源码:

public void callActivityOnCreate(Activity activity, Bundle icicle) {        ...        activity.performCreate(icicle);        ...}
从代码可以看到它做的事情也就是直接调用Activity类的performCreate方法:
final void performCreate(Bundle icicle) {        onCreate(icicle);        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(                com.android.internal.R.styleable.Window_windowNoDisplay, false);         ...        }
而performCreate方法最终调用的就是onCreate方法。所以这里就好比Instrumentation勾住了本应该系统调用的onCreate方法,然后由用户自己来控制勾住的这个方法什么时候执行。

获取Activity中的控件

public void testActivity() throws Exception {          Intent intent = new Intent();        intent.setClassName("com.hustophone.sample", Sample.class.getName());        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        activity = (Activity) getInstrumentation().startActivitySync(intent);        text = (TextView) activity.findViewById(R.id.text1);        button = (Button) activity.findViewById(R.id.button1);}
操作Activity中的控件
getInstrumentation().runOnMainSync(new PerformClick(button));    ...//模拟按钮点击private class PerformClick implements Runnable {        Button btn;        public PerformClick(Button button) {            btn = button;        }        public void run() {            btn.performClick();        }}

3 测试android单元

      该框架基于JUnit,因此既可以直接使用Junit 进行测试,也可以使用Instrumentation 来测试Android 组件,其为Android 应用的每种组件提供了测试基类可以在Eclipse 中方便地创建Android Test Project,并将Test Case直接以Android JUnit的方式运行。
测试示例:
(1)新建一个Instrumentation的Android项目
(2)activity_main.xml内容为:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.xuxu.unittest.MainActivity" ><TextView    android:id="@+id/textView"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/hello_world" /><Button    android:id="@+id/button"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerHorizontal="true"    android:layout_centerVertical="true"    android:text="Button" /></RelativeLayout>
(3)配置AndroidManifest.xml
第一步:添加instrumentation标签
<instrumentationandroid:name="android.test.InstrumentationTestRunner"android:targetPackage="com.xuxu.unittest" ></instrumentation>
第二步:在application标签里面添加uses-library
<uses-library android:name="android.test.runner" /> 
如图:
(4)完成MainActivity,实现点击Button按钮之后TextView的内容由 Hello world! 变为 Hello Android!
实现代码如下:
public class MainActivity extends Activity {    private TextView textView;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView) findViewById(R.id.textView);        button = (Button) findViewById(R.id.button);        button.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                textView.setText("Hello android!");            }        });    }}
(5)对MainActivity进行测试
第一步:建立测试类,可以单独建立一个对应的Android Test Project,也可以就在原项目里面新建测试类,这里选择第二种: 
  1. 右键点击待测项目 > New > Source Folder,文件夹名tests
  2. 右键新建好的tests文件夹 > New > Package, 包名取为待测包名.test, 这里取为com.xuxu.unittest.test
  3. 在包里面新建一个Class:
    Name:MainActivityTest 
    Superclass:android.test.ActivityInstrumentationTestCase2
<pre data-original-code="" public="" void="" testactivity()="" throws="" exception="" {="" "="" data-snippet-id="ext.15db7787d77eff851c5bcce39e20b838" data-snippet-saved="false" data-codota-status="done" style="font-family: Monaco, Consolas, Courier, 'Lucida Console', monospace; font-size: 12px; line-height: 16px; white-space: pre-wrap; background-color: inherit;">实现代码如下:
import com.xuxu.unittest.MainActivity;import android.test.ActivityInstrumentationTestCase2;import android.widget.Button;import android.widget.TextView;public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {private MainActivity mActivity;private TextView textView;private Button button;public MainActivityTest() {    super(MainActivity.class);}@Overrideprotected void setUp() throws Exception {    super.setUp();    mActivity = getActivity();    textView = (TextView) mActivity.findViewById(com.xuxu.unittest.R.id.textView);    button = (Button) mActivity.findViewById(com.xuxu.unittest.R.id.button);}//测试初始化条件public void testInit() {    assertEquals("Hello world!", textView.getText().toString());}//测试点击Button之后TextView的值public void testButton() throws Exception {    //在UI线程中操作    mActivity.runOnUiThread(new Runnable() {        @Override        public void run() {            button.performClick();        }    });    Thread.sleep(500); //加个延时,否则TextView内容还为更改,就已经做断言了    assertEquals("Hello android!", textView.getText().toString());}}
第二步:运行测试。右键项目,选择Run As android JUnit。

测试参考:http://blog.csdn.net/gb112211/article/details/45419669





原创粉丝点击