Android 玩转Junit单元测试

下面通过一个例子讲述一下,单元测试的用法:
1. 新建一个工程名称为HelloJunit

贴出源码:
package com.test.hellojunit;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
     }
}


packagecom.test.hellojunit;

importandroid.test.AndroidTestCase;

importcom.test.hellojunit.service.PersonService;

publicclassPersonServiceTestextendsAndroidTestCase {
     publicvoidtestSave()throwsThrowable {
          // 声明并实例化PersonService
          PersonService mPersonService =newPersonService();
          // 调用Save方法
          mPersonService.save();
     }
}

packagecom.test.hellojunit.service;

publicclassPersonService {
     publicvoidsave() {
          String str ="android";
          IntegermInteger=newInteger(str);
     }
}

源码编写完成之后,最后需要配置AndroidManifest.xml文件,见红色加粗部分:

<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
   package="com.test.hellojunit"
   android:versionCode="1"
   android:versionName="1.0">

   <uses-sdk
       android:minSdkVersion="16"
       android:targetSdkVersion="17"/>

   <application
       android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme">

       <!-- 使用单元测试库 -->
       <uses-libraryandroid:name="android.test.runner"/>

       <activity
           android:name="com.test.hellojunit.MainActivity"
           android:label="@string/app_name">
           <intent-filter>
               <actionandroid:name="android.intent.action.MAIN"/>

               <categoryandroid:name="android.intent.category.LAUNCHER"/>
           </intent-filter>
       </activity>
   </application>

   <!-- 声明Android框架和目标测试包 -->
   <instrumentation
       android:name="android.test.InstrumentationTestRunner"
       android:label="Hello Android Test"
       android:targetPackage="com.test.hellojunit"/>

</manifest>

说明:
(1).<uses-library android:name = "android.test.runner" /> 这一句必须放在application内部,与四大组建属于同一级位置。
 (2). 
    <instrumentation
        android:name ="android.test.InstrumentationTestRunner"
        android:targetPackage ="com.test.hellojunit" />
注:
instrumentation标签必须放在application外部,且:
android:name ="android.test.InstrumentationTestRunner"是固定的,即android:name的属性值是android.test.InstrumentationTestRunner

android:targetPackage的属性值为应用的包名,与package= "com.test.hellojunit"的值相同


需要注意:
A。单元测试类需要继承"android.test.AndroidTestCase"
B. 单元测试方法需要声明为Public类型
C。单元测试方法的返回值类型为void
D. 按照Junit3的规范要求,单元测试方法的方法命名需要以test开头
E。单元测试方法需要声明向单元测试框架抛出异常

下面开始运行测试:
1.打开继承AndroidTestCase的测试类
2.打开Outline视图



运行结果:

从上面信息可以看出,有一个错误,定位到选中行,双击可以进去查看:
public class PersonService {
     public void save() {
          String str = "android";
          Integer mInteger = new Integer(str) ;
     }
}

得知:str = "android"是一个无效的格式,如果改成str = "2014"就会得到正确的结果
 
(原文链接:http://blog.csdn.net/yelangjueqi/article/details/21233211 欢迎转载,尊重他人劳动成果,转载时请注明出处!)




 
Junit 单元测试第二种方法
独立建立一个测试工程:
1.新建一个测试工程:

选中Android Test Project   然后Next ..



选中一个待测试的工程,测出很关键,决定着要测试哪个工程

finish之后,就独立创建了一个测试工程:
打开清单文件:
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
   package="com.test.actionabletoastbar.test"
   android:versionCode="1"
   android:versionName="1.0">

   <uses-sdkandroid:minSdkVersion="15"/>

   <instrumentation
       android:name="android.test.InstrumentationTestRunner"
       android:targetPackage="com.test.actionabletoastbar"/>

   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name">
       <uses-libraryandroid:name="android.test.runner"/>
   </application>

</manifest>

发现已经自动配置完成:
<uses-library android:name = "android.test.runner" />
<instrumentation
        android:name ="android.test.InstrumentationTestRunner"
        android:targetPackage ="com.test.actionabletoastbar" />

android:targetPackage的属性值即是前面步骤选择时的工程的包名:
 
然后,在com.test.actionabletoastbar.test包下,新建一个测试类HelloJunit

 
packagecom.test.actionabletoastbar.test;

importcom.test.actionabletoastbar.Utils;

importandroid.test.AndroidTestCase;

publicclassHelloJunitextendsAndroidTestCase {
     publicvoidtestUtils() {
          Utils mUtils =newUtils();
          mUtils.test();
     }
}
在上面测试类里,你会发现,编写时,测试环境会自动引入你要测试的工程里面的类:如:com.test.actionabletoastbar.Utils

测试过程同方法一,不再赘述。

 




对Activity中的 querydata方法进行单元测试:
源码:
publicclassMainActivityextendsActivity {
     @Override
     protectedvoidonCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          //querydata();
     }

     // 通过ContentProvider查询数据
     publicvoidquerydata(Context context) {
          
          ContentResolver mContentResolver = context.getContentResolver();

          String word ="word_";
          String detail ="detail_";

          // selection相当于where关键字后面的部分,不包括where
          String selection = Words.Word.WORD+" like ? or "+ Words.Word.DETAIL
                   +" like ?";
          String[] selectionArgs =newString[] {"%"+ word +"%",
                   "%"+ detail +"%"};

          Cursor cursor = mContentResolver.query(
                   Uri.parse("content://com.test.providers.dictprovider/words"),
                   null, selection, selectionArgs,null);
          if(cursor !=null) {
              while(cursor.moveToNext()) {
                   String wordValue = cursor.getString(cursor
                             .getColumnIndex(Words.Word.WORD));
              }
          }
     }

}

在同包名下,新建一个测试类:
packagecom.test.dictresolver;

importandroid.content.Context;
importandroid.test.AndroidTestCase;

publicclassTestextendsAndroidTestCase {
     publicvoidtest() {
          Context context = getContext().getApplicationContext();
          MainActivity activity =newMainActivity();
          activity.querydata(context);
     }
}
 
右键点击,运行:

注:在测试类中获取当前的上下文,可以如下获取:
Context context = getContext().getApplicationContext();

最后在配置一下清单文件!!
posted @ 2014-03-14 13:12  行走的思想  阅读(12)  评论(0编辑  收藏  举报  来源