---
title: "Android单元测试之Activity测试"
author: "nick714"
date: "2011-08-25T11:14:57Z"
tags: []
categories: ["移动开发"]
slug: "android-activity"
draft: false
lastmod: "2011-10-21T17:45:47Z"
id: 1157667
url: "https://nick714.iteye.com/blog/1157667"
---

Activity测试类有三个，包含主要的[ActivityInstrumentationTestCase2](http://developer.android.com/reference/android/test/ActivityInstrumentationTestCase2.html)和[ActivityUnitTestCase](http://developer.android.com/reference/android/test/ActivityUnitTestCase.html)，当然，如果测试单个Activity，还可以用到[SingleLaunchActivityTestCase](http://developer.android.com/reference/android/test/SingleLaunchActivityTestCase.html)。

       1.[ActivityInstrumentationTestCase2](http://developer.android.com/reference/android/test/ActivityInstrumentationTestCase2.html)

         运行测试多个应用下的多个Activity，可以发送虚拟Intent,不允许使用虚拟化的Contexts或者Application.如果要向当前测试的Activity发送Intent的话，一定要在getActivity()方法之前就发送，在getActivity()方法之后发送是不起作用的。

        怎么建立测试项目就不多讲了，现在看看测试该Activity的代码：

 

public class AutoPlayActivityTest extends ActivityInstrumentationTestCase2&lt;AutoPlayActivity&gt; {

 

ImageView imageView;

AutoPlayActivity mActivity;

String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator;

String\[] uuuu;

public AutoPlayActivityTest() {

super("lichunan.lcn.activity.AutoPlayActivity",AutoPlayActivity.class);

}

 

@Override

protected void setUp() throws Exception {

// TODO Auto-generated method stub

super.setUp();

uuuu = new String\[]{SDCARD+"080806012774292.jpg",SDCARD+"20110801\_121726.jpg"};

Intent intent = new Intent();

intent.putExtra("allPhotoPath", uuuu);

//mActivity.setIntent(intent);

setActivityIntent(intent);

mActivity = this.getActivity();

imageView = (ImageView)mActivity.findViewById(R.id.imageView);

}

 

@Override

protected void tearDown() throws Exception {

super.tearDown();

}

public void testAutoPlay(){

}

}

             说明一下，setUp() 是在执行所有方法之前先执行，tearDown()在执行所有方法之后再执行。

       其实 testAutoPlay()也不是没用，因为只有setUp和tearDown方法的话，没有测试的方法，好像会报send 1,receive 0的错误，具体什么原因我也不知道，哪位大牛知道的，希望能够在后面留言！

        另外，要注意的是，测试程序里super("lichunan.lcn.activity.AutoPlayActivity",AutoPlayActivity.class)的第一个参数一定要对应Mainfest.xml文件中 &lt;instrumentation android:targetPackage=“”&gt;中的字段，也就是AutoPlayActivity.class对应的包。