2

I have made an application that deals with SQLite database by opening, retrieving data from, and inserting data to it. Now I want to test my methods.

So , I have two classes, one "SQLiteHelper" which extends SQLiteOpenHelper to open,create,and upgrade the database, and the other is a DataSource class, that makes an SQLiteDatabase object,and contains all my methods that deals with the database.

So for calling any method I need to call the open method in the SQLiteHelper class, catch the result in an SQLiteDatabse object,then make an object of the DataSource class,and finally call the method( which contains a cursor as a result of a rawquery for example).

I know that it won't work with simple JUnit test, and I've read about Mock Objects, but I still don't understand how I can use it in my case.

apaderno
  • 28,547
  • 16
  • 75
  • 90
user1753461
  • 45
  • 2
  • 4
  • "the other is a DataSource class, that makes an SQLiteDatabase object" - this is not clear. `SQLiteHelper` should create `SQLiteDatabase` object. Can you provide some code of your `DataSource` class to clarify the problem. – olshevski Oct 22 '12 at 10:47
  • public class DataSource { private static SQLiteHelper dbHelper = null; SQLiteDatabase database;public void openDatabase(Context context) { if (dbHelper == null) { dbHelper = new SQLiteHelper(context); dbHelper.openDataBase(SQLiteDatabase.OPEN_READWRITE); database = dbHelper.myDataBase; } } – user1753461 Oct 22 '12 at 11:00
  • Oh, I see. Nothing important in this class. Check my answer anyway – olshevski Oct 22 '12 at 11:05
  • If you are satisfied with answer, please mark it as accepted. – olshevski Oct 22 '12 at 12:24

1 Answers1

4

I know that it won't work with simple JUnit test

It will. Just call your methods as usual and check results for correctness.

The only important thing is that you should prefer to use IsolatedContext for your database creation. In this case your original database file from the app will remain unmodified. All tests will work with separate testing database file which can be modified or even deleted as many times as you want.

You can acquire proper IsolatedContext from ProviderTestCase2. (You can also look ProviderTestCase2 sources to understand how it works.)

olshevski
  • 4,971
  • 2
  • 35
  • 34