單元測試環境搭建:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.db.demo" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <instrumentation android:targetPackage="com.db.demo" android:name="android.test.InstrumentationTestRunner" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".DBActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-library android:name="android.test.runner" /> </application></manifest>
對上篇文章的資料庫中的業務類進行測試:
package com.db.demo;import java.util.List;import android.test.AndroidTestCase;import android.util.Log;public class PersonServiceTest extends AndroidTestCase {public void testCreateDB() throws Throwable {DBOpenHelper dbOpenHelper = new DBOpenHelper(this.getContext());dbOpenHelper.getWritableDatabase();}public void testInsert() throws Throwable {PersonService ps = new PersonService(this.getContext());Person p = new Person();p.setName("abc");ps.insert(p);p = new Person();p.setName("def");ps.insert(p);p = new Person();p.setName("ghi");ps.insert(p);p = new Person();p.setName("dd");ps.insert(p);p = new Person();p.setName("ff");ps.insert(p);p = new Person();p.setName("ee");ps.insert(p);p = new Person();p.setName("ww");ps.insert(p);p = new Person();p.setName("hh");ps.insert(p);p = new Person();p.setName("jj");ps.insert(p);p = new Person();p.setName("uu");ps.insert(p);}public void testUpdate() throws Throwable {PersonService ps = new PersonService(this.getContext());Person p = new Person();ps.update(p);}public void testDelete() throws Throwable {PersonService ps = new PersonService(this.getContext());ps.delete(1);}public void testFind() throws Throwable {PersonService ps = new PersonService(this.getContext());Person p = ps.find(1);Log.d(AppConstant.TAG, p.toString());}public void testGetScrollData() throws Throwable {PersonService ps = new PersonService(this.getContext());List<Person> persons = ps.getScrollData(0, 3);for(Person person : persons) {Log.d(AppConstant.TAG, person.toString());}}public void testGetCount() throws Throwable {PersonService ps = new PersonService(this.getContext());Log.d(AppConstant.TAG, ps.getCount() + "");}}