1.首先我们需要一个空白的eclipse android工程
2.然后修改AndroidManifest.xml
在<application></application>标签里面加入一句<uses-library android:name="android.test.runner"/>用于添加单元测试
在<application></application>标签里面加入<instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.example.android_SQLite"></instrumentation>
具体可参考http://www.cnblogs.com/feisky/archive/2010/07/23/1783826.html
3.在src中新建一个类DbSQLiteHelper用于构建SQLite数据库
package com.example.android_sqlite; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; public class DbSQLiteHelper extends SQLiteOpenHelper { @Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub } @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub } }
创建好了以后发现eclipse中报错,Must define an explicit constructor。我们需要写一个构造函数。
private static String NAME = "mydb";
private static int VERSION = 1; public DbSQLiteHelper(Context context) {
// context 上下文 name数据库的名称 version数据库版本号
// 原型是super(context, name, factory, version);
// TODO Auto-generated constructor stub
super(context, NAME, null, VERSION);
}
4.DbSQLiteHelper的onCreate中编写sql语句来创建数据库
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
String sql = "create table person(id integer primary key autoincrement,name varchar(20),address varchar(20))";
arg0.execSQL(sql);
}
5.新建一个Test类,必须继承AndroidTestCase
package com.example.android_db.test; import com.example.android_db.db.DbSQLiteHelper; import android.test.AndroidTestCase; public class Test extends AndroidTestCase { public Test() {
// TODO Auto-generated constructor stub
}
public void createDB(){
DbSQLiteHelper dbSQLiteHelper = new DbSQLiteHelper(getContext());
dbSQLiteHelper.getReadableDatabase(); } }
6.然后选择方法createDB()右键选中Android JUit Test
测试成功