While trying to develop some unit tests for the project that I'm working on I hit a wall where I need to test DB-behaviour. I'm trying to create a in-memory DB(SQLite)
While I thought that this rather basic test would do as asked, it always returns a NULL database, which is not what I expected.
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");
}
}
}
I have looked at several different solutions on Stackoverflow, but none seemed to be able to point me to the right solution. They are listed here
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?
What am I doing wrong that I get a null db, but not any kind of error or exception?