【安卓篇】Android单元测试初探Instrumentation

来源:互联网 发布:张学友 深海知乎 编辑:程序博客网 时间:2024/06/02 12:48

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

【安卓篇】Android单元测试初探——Instrumentation

  可以看出android中的测试方法主要有AndroidTextCase和InstrumentationTextCase。在这篇文章中,我将介绍Instrumentation这种测试方法,那么什么是Instrumentation?

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

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

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

<pre name="code" class="java">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 {    privateTextView myText = null;    privateButton button = null;    @Override    public voidonCreate(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           publicvoid onClick(View arg0) {              myText.setText("HelloAndroid");            }       });    }    publicintadd(int i, int j) {       return(i + j);    }}

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

  2.在src文件夹中添加一个测试包,在测试包中添加一个测试类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 {    privateSample sample = null;    privateButton button = null;    privateTextView text = null;      @Override    protectedvoid setUp()  {       try {           super.setUp();       } catch (Exception e) {           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);    }       @Override    protectedvoid tearDown()  {       sample.finish();       try {           super.tearDown();       } catch (Exception e) {           e.printStackTrace();       }    }     public voidtestActivity() 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());    }       privateclass PerformClick implements Runnable {       Button btn;       public PerformClick(Button button) {           btn = button;       }       public void run() {           btn.performClick();       }    }        public voidtestAdd() 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. Thismethod is called before a test is executed.

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

  setUp ()用来初始设置,如启动一个Activity,初始化资源等。
  tearDown ()则用来垃圾清理与资源回收。

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

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

0 0