I’ve implemented access to a database using SQLiteOpenHelper from the android.database package within some classes (with pattern DAO).
I wrote some junit tests for these classes using an AndroidTestCase but this causes the tests to use the same database as the application.
I read that the ProviderTestCase2 or RenamingDelegatingContext can be used to test the database separately. Unluckily I couldn’t find any nice tutorial/example that shows how to test a database with ProviderTestCase2/RenamingDelegatingContext.
Can anyone point me somewhere OR give me some tip OR share some code for database testing?!
Cheeerrrrsss!!
Giorgio
Both the
ProviderTestCaseandRenamingDelegatingContextwill destroy the database if one already exists before opening it within it’s context, so in that sense they both have the same low-level approach towards opening a SQLite database.You leverage this by opening the database in your fixture in
setUp(), which will then ensure that your working with a fresh database before each test case.I would suggest that you go for writing content providers rather than creating database adapters. You can use a common interface for accessing data, be it stored in the DB or somewhere over the network, the design of content providers can be accommodated to access such data at the cost of a bit of IPC overhead involved that most of us shouldn’t have to care about.
If you did this for accessing a SQLite database, the framework would completely manage the database connection for you in a separate process. As added beef, the
ProviderTestCase2<ContentProvider>completely bootstraps a test context for your content provider without you having to a write a single line of code.But, that’s not said it isn’t such a huge effort to do the bootstrapping yourself. So supposing you had a database adapter as such; we’ll just focus on
open()for getting write access to our database, nothing fancy:Then you could write your test as such:
So what’s happening here is that the context implementation of
RenamingDelegatingContext, onceMyAdapter(context).open()is called, will always recreate the database. Each test you write now will be going against the state of the database afterMyAdapter.DATABASE_CREATE_STATEMENTis called.