Android工程 单元测试

一、创建测试工程

  1. New > Project > Android > Android Test Project.

  1. 添加测试用例类

    添加新类,基类设置为android.test.ActivityInstrumentationTestCase2<HelloAndroid>

  2. 添加构造函数

    添加setUp()方法,这个方法在所有的测试之前进行变量和测试环境的初始化。

    @Override

        protected void setUp() throws Exception {

            super.setUp();

            mActivity = this.getActivity();

            mView = (TextView) mActivity.findViewById(com.example.helloandroid.R.id.textview);

            resourceString = mActivity.getString(com.example.helloandroid.R.string.hello);

        }

  3. 添加testPreconditions()方法,检查初始化环境,只执行一次

    public void testPreconditions() {

          assertNotNull(mView);

        }

  4. 添加单元测试

    public void testText() {

          assertEquals(resourceString,(String)mView.getText());

        }

  5. 测试 Run As... > Android JUnit Test

二、测试类的选择

   1、测Activity中的方法

        写一个测试类,让它继承自ActivityInstrumentationTestCase2<AHttpServerActivity>。

        首先,重写构造函数

1 public ActivityTest2() {
2           super("com.test.testA",AActivity.class);
3     }

      其中super()中两个参数,前者为待测Activity的包名,后者为待测Activity的.class后缀名称。

      其次,实现setup(),在setup中调用getActivity,能启动该Activity,方便后面调Activity的方法。

1 public void setUp() throws Exception {
2         super.setUp();
3         a = getActivity();        
4     }

      再次,写测试方法,测Activity的方法。

1      @MediumTest
2      public void testHandler()  {                
3            AActivity.sendMsgToActivity("http error", false);
4      }

2、测试一般类的方法

写一个测试类,让它继承自AndroidTestCase。 

重写setUp() ,在里面进行类环境的初始化 。
重写tearDown(),在里面进行环境的销毁。

写下面的函数,测相应的类的方法:
public void testXxxx() throws Exception(){
    ...
}
**这里抛出的异常会被测试框架捕获

 

注:在测试方法里记得让Thread.sleep(),这样有一些不是同步的方法得以执行。

三、覆盖率统计工具

1、下载工具apache-ant-1.8.4,并将它的解压缩后的路径添加到path中去。

2、编写批处理(.bat文件)文件,清除上一次统计的文件

cd D:\test\test\A

del local.properties build.xml  
rmdir /q /s libs

cd D:\test\test\ATest
del local.properties build.xml  ant.properties
rmdir /q /s coverage

其中D:\test\test\A为被测工程的目录,D:\test\test\ATest为测试工程的目录。

3、执行下列命令

android update project -p D:\test\test\A

android update test-project -m D:\test\test\A -p D:\test\test\ATest

ant clean emma debug install test

即可在测试工程目录下生成converage文件夹,其中就得到了统计覆盖率的数据。

posted on 2013-01-06 15:09  meizixiong  阅读(2086)  评论(0编辑  收藏  举报