FileDocCategorySizeDatePackage
DatabaseErrorHandlerTest.javaAPI DocAndroid 5.1 API4679Thu Mar 12 22:22:12 GMT 2015android.database

DatabaseErrorHandlerTest

public class DatabaseErrorHandlerTest extends android.test.AndroidTestCase

Fields Summary
private android.database.sqlite.SQLiteDatabase
mDatabase
private File
mDatabaseFile
private static final String
DB_NAME
private File
dbDir
Constructors Summary
Methods Summary
protected voidsetUp()


    
         
        super.setUp();
        dbDir = getContext().getDir(this.getClass().getName(), Context.MODE_PRIVATE);
        mDatabaseFile = new File(dbDir, DB_NAME);
        if (mDatabaseFile.exists()) {
            mDatabaseFile.delete();
        }
        mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null,
                new MyDatabaseCorruptionHandler());
        assertNotNull(mDatabase);
    
protected voidtearDown()

        mDatabase.close();
        mDatabaseFile.delete();
        super.tearDown();
    
public voidtestDatabaseIsCorrupt()

        mDatabase.execSQL("create table t (i int);");
        // write junk into the database file
        BufferedWriter writer = new BufferedWriter(new FileWriter(mDatabaseFile.getPath()));
        writer.write("blah");
        writer.close();
        assertTrue(mDatabaseFile.exists());
        // since the database file is now corrupt, doing any sql on this database connection
        // should trigger call to MyDatabaseCorruptionHandler.onCorruption
        try {
            mDatabase.execSQL("select * from t;");
            fail("expected exception");
        } catch (SQLiteDiskIOException e) {
            /**
             * this test used to produce a corrupted db. but with new sqlite it instead reports
             * Disk I/O error. meh..
             * need to figure out how to cause corruption in db
             */
            // expected
            if (mDatabaseFile.exists()) {
                mDatabaseFile.delete();
            }
        } catch (SQLiteException e) {
            
        }
        // database file should be gone
        assertFalse(mDatabaseFile.exists());
        // after corruption handler is called, the database file should be free of
        // database corruption
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null,
                new MyDatabaseCorruptionHandler());
        assertTrue(db.isDatabaseIntegrityOk());
    
public voidtestNoCorruptionCase()

        new MyDatabaseCorruptionHandler().onCorruption(mDatabase);
        // database file should still exist
        assertTrue(mDatabaseFile.exists());