Testing SQLite database in Robolectric

后端 未结 3 1363
无人及你
无人及你 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:58

    The code linked in the accepted answer did not work for me; it may be out of date. Or perhaps my setup is just different. I am using Robolectric 2.4 snapshot, which does not seem to include a ShadowSQLiteOpenHelper, unless I missed something. In any case, I figured out a solution. Here's what I did:

    1. I created a class called ShadowSQLiteOpenHelper and copy-pasted the contents of the code linked above (https://github.com/waltsu/robolectric/blob/de2efdca39d26c5f18a3d278957b28a555119237/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteOpenHelper.java), and fixed the imports.
    2. Following the instructions on http://robolectric.org/custom-shadows/ for using custom shadows, I annotated my test class with @Config( shadows = { ShadowSQLiteOpenHelper.class } ). No need for a custom test runner.
    3. In my tests, I instantiated my subclass of SQLiteOpenHelper, passing in a new Activity() as the Context (Robolectric happily takes care of that), and used it per usual.

    Now, at this point, I noticed that an actual database file was getting created locally: after the first run of a test that used my SQLiteOpenHelper subclass, I kept getting an SQLiteException on subsequent tests because my table already existed; and I could see a file called "path" and a file called "path-journal" sitting in my local repository. This confused me because I was under the impression that the shadow class was using an in-memory database.

    It turns out the offending line in the shadow class is:

    database = SQLiteDatabase.openDatabase( "path", null, 0 );
    

    in both getReadableDatabase() and getWriteableDatabase(). I knew that the real SQLiteOpenHelper could create an in-memory database, and after looking at the source to see how it's done, I replaced the above line with:

    database = SQLiteDatabase.create( null );
    

    after which, everything seems to work. I am able to insert rows and read them back.

    Hopefully this helps someone else.

    One weird thing that happened to me that isn't exactly related to this question, but might help someone further, is that I'm also using jmockit, and I had used it in one test in the same class; but for some reason, this caused my custom shadow class to not be used. I switched to Mockito for just that class, and it works fine.

提交回复
热议问题