android单元测试

要在android中进行单元测试,主要分以下两步:
1.写一个测试类继承自android.test.AndroidTestCase
2.在AndroidManifest.xml文件中进行配置

步骤1代码:
package com.mmqzlj.test;

import com.mmqzlj.utils.DownloadText;

import android.test.AndroidTestCase;

public class DownloadTextTest extends AndroidTestCase {
   public void testDownload(){
    DownloadText.test();
  }
  @Override
   protected void setUp() throws Exception {
     // TODO Auto-generated method stub
     super.setUp();
  }
  @Override
   protected void tearDown() throws Exception {
     // TODO Auto-generated method stub
     super.tearDown();
  }
  @Override
   public void testAndroidTestCaseSetupProperly() {
     // TODO Auto-generated method stub
     super.testAndroidTestCaseSetupProperly();
  }

}

setUp() ,tearDown(),testAndroidTestCaseSetupProperly() 这3个方法都是覆写父类的。setUp()设置测试前需要执行的内容,比如建立一个连接等,tearDown()是在测试执行后需要进行的动作,比如关闭连接等。testAndroidTestCaseSetupProperly()主要用于检验测试所用参数。如果不需要这三个方法也可以不覆写。

步骤2代码:
<? xml version ="1.0" encoding ="utf-8" ?>
< manifest xmlns:android ="http://schemas.android.com/apk/res/android"
             package ="com.mmqzlj.activity"
             android:versionCode ="1"
             android:versionName ="1.0" >


         < application android:icon ="@drawable/icon" android:label ="@string/app_name" >
         < uses-library android:name ="android.test.runner" > </ uses-library >
                 < activity android:name =".MainActivity"
                                     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-permission android:name ="android.permission.INTERNET" />
         < instrumentation android:name ="android.test.InstrumentationTestRunner" android:targetPackage ="com.mmqzlj.activity" > </ instrumentation >
</ manifest >

写好AndroidTestcase,然后就是在AndroidManifest.xml增加两句话。一是在 application 节点下增加 < uses-library android:name ="android.test.runner" > </ uses-library >。二是增加 < instrumentation android:name ="android.test.InstrumentationTestRunner" android:targetPackage ="com.mmqzlj.activity" > </ instrumentation >

大家可能注意到了,我这里的DownloadTextTest是在com.mmqzlj.test这个package下面,为何我写成 com.mmqzlj.activity。 答案是写成com.mmqzlj.test执行时会报找不到com.mmqzlj.test包错,估计跟xml最顶部配置的package包有关系。总之写成 com.mmqzlj.activity能顺利找到com.mmqzlj.test.DownloadTextTest并且执行以test开头的方法就是了。至于原因,请有识之士告知。

好了,配置完毕之后,在eclipse中右键run as ->Android Junit Test就可以了。

你可能感兴趣的:(android,android,单元测试,职场,AndroidTestCase,休闲)