Android:junit测试的步骤

来源:互联网 发布:新浪集团网络运营 编辑:程序博客网 时间:2024/06/01 09:20

在实际开发中,Junit测试在android的开发中占有无以伦比的作用,也是一个合格程序员必须掌握的一门技术。

关于在android中如何使用数据库,请参照 http://blog.csdn.net/liuhe688/article/details/6715983 这位大哥的解说,他说的已经很详细。

1.首先在AndroidManifest.xml中加入下面代码:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"   <strong><span style="color:#ff0000;"> package="com.example.db"</span></strong>    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >                <!-- junit测试需要导入的包 -->        <uses-library android:name="android.test.runner" />                        <activity            android:name="com.bjbsh.activity.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>    <!-- 指定junit测试的包名,此声明必须放在application外面 -->    <instrumentation android:name="android.test.InstrumentationTestRunner"        <strong><span style="color:#330099;">android:targetPackage="com.example.db"</span></strong> android:label="test for my App" />    </manifest>
注:红颜色和蓝颜色标注的地方,包名相同,如果包名不相同,在运行junit测试时会出现包找不到的异常


2.其次是在你junit测试的类中,该类要继承AndroidTestCase类

package com.bjbsh.test;import android.test.AndroidTestCase;import android.util.Log;import com.bjbsh.domain.Person;import com.bjbsh.service.DBOpenHelper;import com.bjbsh.service.PersonService;public class PersonServiceTest extends AndroidTestCase {private final String TAG="PersonService的junit测试";/** * 初始化数据库 * 并在数据库中创建一张person表 */public void create() {DBOpenHelper helper = new DBOpenHelper(this.getContext());Log.i(TAG,"数据库创建成功");}/** * 删除数据库 */public void deleteDatabase() {DBOpenHelper helper = new DBOpenHelper(this.getContext());helper.deleteDatabase(getContext());Log.i(TAG, "删除成功!");}/** * 向person表中插入一条数据 */public void add() {PersonService service = new PersonService(this.getContext());Person person = new Person("zhensan", 23, "3838384438");person.setId(20);service.add(person);Log.i(TAG, "插入成功!");}}

3.最后,在outline中右键单击要测试的方法,Run as->Android Junit Test即可。


0 0