Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Robolectric (2.3) test using database

Due to last release of Robolectic to version 2.3, it's written that (https://github.com/robolectric/robolectric/releases):

Robolectric now uses a real implementation of SQLite instead of a collection of shadows and fakes. Tests can now be written to verify real database behavior.

I haven't found any "How to" documentation. I'd like to know how should I implement test on e.g. Activity using SQLiteDatabase query. Where should I put .db file so a test uses it.

like image 677
light Avatar asked May 22 '14 13:05

light


1 Answers

You will need to put the .db file under src/test/resources/ folder.

For example, sample.db

Then in your unit test setUp() call:

@Before
public void setUp() throws Exception {
    String filePath = getClass().getResource("/sample.db").toURI().getPath();

    SQLiteDatabase db = SQLiteDatabase.openDatabase(
        (new File(filePath)).getAbsolutePath(), 
        null, 
        SQLiteDatabase.OPEN_READWRITE);

   // perform any db operations you want here
}
like image 96
lordhong Avatar answered Oct 23 '22 01:10

lordhong