在尝试为我正在从事的项目开发一些单元测试时,遇到了需要测试DB行为的难题。 我正在尝试创建一个内存数据库(SQLite)
虽然我认为这个相当基本的测试可以按照要求进行,但是它总是返回一个NULL数据库,这不是我期望的。
package be.wgkovl.evdt.Util;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.test.mock.MockContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith( PowerMockRunner.class )
public class ClassForStack {
SQLiteDatabase db;
Context context;
private Cursor test() {
if (db != null) {
return db.rawQuery("Select * from myTable", new String[]{});
} else {
System.out.println("Db is null :-(");
}
return null;
}
private String[] emtpyArgument = new String[]{};
@Before
public void setup() {
System.out.println("Setting up");
context = new MockContext();
SQLiteOpenHelper dummy = new SQLiteOpenHelper(context, "SomeName.memory", null, 1) {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public void onCreate(SQLiteDatabase db) {
}
};
String basicInitQuery = "CREATE TABLE IF NOT EXISTS myTable(id INTEGER PRIMARY KEY DESC, value TEXT)";
String basicInsertQuery = "INSERT INTO myTable(id, value) VALUES (1,?)";
db = dummy.getWritableDatabase();
}
@Test
public void baseDbTest() {
Cursor c = test();
if (c != null) {
System.out.println(c.getColumnNames());
System.out.println(c.getColumnCount());
System.out.println("Starting test");
}
}
}
我已经研究了Stackoverflow上的几种不同解决方案,但是似乎没有一个能够为我提供正确的解决方案。它们在这里列出
getWritableDatabase returns null
Android Sqlite always null even after calling getWritableDatabase()
Create SQLite database in android
SQLite getReadableDatabase() returns NULL
SQLiteOpenHelper failing to call onCreate?
我得到一个空的db但没有任何类型的错误或异常,这是怎么做的?
答案 0 :(得分:0)
您是否忘记在onCreate()中创建表?
db.execSQL(basicInitQuery);