Skip to content

Instantly share code, notes, and snippets.

@richardleggett
Last active June 26, 2021 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardleggett/8318730eccb3cdc6316d to your computer and use it in GitHub Desktop.
Save richardleggett/8318730eccb3cdc6316d to your computer and use it in GitHub Desktop.
Using SQLCipher with ProviderTestCase2 Example
package my.app.test;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncInfo;
import android.os.Environment;
import android.test.ProviderTestCase2;
import android.util.Log;
import net.sqlcipher.database.SQLiteDatabase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
/**
* Base class for any test cases that use the MyContentProvider. Automatically uses a
* MockContentResolver to avoid modifying the regular database.
*/
abstract public class BaseMyContentProviderTestCase extends ProviderTestCase2<MyContentProvider> {
private static final String TAG = BaseMyContentProviderTestCase.class.getSimpleName();
/**
* Default constructor as required
*/
public BaseMyContentProviderTestCase() {
super(MyContentProvider.class, MyContentProvider.AUTHORITY);
}
@Override
protected void setUp() throws Exception {
super.setUp();
// initialize SQLCipher with correct Context and file path for these tests
SQLiteDatabase.loadLibs(getMockContext(),
getMockContext().getDatabasePath(MyDatabaseHelper.DB_NAME).getParentFile());
// make sure SyncAdapter doesn't try to run
ContentResolver.cancelSync(SyncAdapter.getAccount(getMockContext()),
MyContentProvider.AUTHORITY);
// wait here until SyncAdapter finishes (or we will get a ReadOnlyDatabaseException after
// due to the :sync process accessing at the same time)
boolean isSyncing;
do {
isSyncing = false;
for (SyncInfo syncInfo : ContentResolver.getCurrentSyncs()) {
if(syncInfo.authority.equals(MyContentProvider.AUTHORITY)) {
isSyncing = true;
break;
}
}
Thread.sleep(10);
} while(isSyncing);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
getMockContext().getDatabasePath(MyDatabaseHelper.DB_NAME).delete();
}
}
@richardleggett
Copy link
Author

One issue to tackle, the above stops an ongoing SyncAdapter and waits for it to finish before running the next test. Debugging shows it is running on start due to the setSyncAutomatically() in the Application setup. But technically it could also start again during the test (e.g. due to network "tickle") as it's a different process. Need to permanently disable automatic syncing once it's been set without side effects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment