samedi 28 mai 2016

SQLiteDatabse unitTest

I have a problem with SQLDatabase testing.

Here some parts of my code, I skip unimportant parts of code like TetsObject declaration (contain 2 fields: String id and String Title) and definition of database table and its fields.

build.gradle:

android {
    ...
    testOptions { unitTests.returnDefaultValues = true }
}

dependencies { testCompile 'junit:junit:4.12' }

DatabaseHelper:

public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database.db";
private static final String TABLE_TABLE_CREATE = "...";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(TABLE_TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { ... } }

TableOperations:

public class TableOperations {
private SQLiteDatabase mDatabase;

public TableOperations(SQLiteDatabase database) {
    mDatabase = database;
}

public List<TestObject> getEnteries() { ... }
public TestObject getEntery(String id) { ... }
public void addEntery(TestObject object) { ... }
public void updateEntery(String id, TestObject object) { ... } }

Test:

public class ExampleUnitTest extends AndroidTestCase {
private SQLiteOpenHelper mDatabaseHelper;

@Override
protected void setUp() throws Exception {
    super.setUp();

    Context context =new RenamingDelegatingContext(getContext(), "test_");
    mDatabaseHelper = new DatabaseHelper(context);
}

@Override
protected void tearDown() throws Exception {
    super.tearDown();

    mDatabaseHelper.close();
}

@Test
public void testDatabaseNotNull() throws Exception {
    assertNotNull("Database is null", mDatabaseHelper.getWritableDatabase());
}

@Test 
public void testDatabaseReading() throws Exception{
    // insert some data to database
    TableOperations operations = new TableOperations(mDatabaseHelper.getWritableDatabase());
    // assertEquals test database reading here
} }

I want to test database operations but can't because firs test always failed, mDatabase always null.

Aucun commentaire:

Enregistrer un commentaire