Testing SQLite database in Robolectric

后端 未结 3 1354
无人及你
无人及你 2020-12-14 19:27

I\'m trying to test a simple SQLite database using Robolectric in my Android application. I\'m putting in some values, but when reading them back 0 rows are returned.

<
3条回答
  •  抹茶落季
    2020-12-14 19:34

    NOTE: This answer is outdated. If you are using Roboletric 2.X, please see https://stackoverflow.com/a/24578332/850787

    The problem is that Robolectric's SQLiteDatabase is stored only in memory, so when you call getReadableDatabase or getWritableDatabase, the existing database will be overridden with new empty database.

    I was running to the same problem and only solution I found was that I needed to fork the Robolectric project and added ShadowSQLiteOpenHelper to save database if same context is given two times. However the problem with my fork is that I had to 'disable' close()-function when contex is given because otherwise Connection.close() will destroy the database in memory. I have made pull request for it but it isn't merged to project yet.

    But feel free to clone my version and it should fix your problem (If I understood it correctly :P ). It can be found on GitHub: https://github.com/waltsu/robolectric

    Here is a example how to use the modification:

    Context c = new Activity(); 
    SQLiteOpenHelper helper = new SQLiteOpenHelper(c, "path", null, 1); 
    SQLiteDatabase db = helper.getWritableDatabase(); 
    // With the db write something to the database 
    db.query(...); 
    SQLiteOpenHelper helper2 = new SQLiteOpenHelper(c, "path", null, 1); 
    SQLitedatabase db2 = helper2.getWritableDatabase(); 
    // Now db and db2 is actually the same instance 
    Cursor c = db2.query(...) ; // Fetch the data which was saved before 
    

    Ofcourse you don't need to create new SQLiteOpenHelper, but that is just example that passing same context to two different SQLiteOpenHelper will give same database.

提交回复
热议问题