Skip to content Skip to sidebar Skip to footer

How To Test Android Sqlite With Junit?

I created a simple Android app (HelloWorld like) an dnow I would add operation to save sample data with mockdao (just a List to manage data). In future, I would persist data in sql

Solution 1:

You should take a look at robolectric : http://robolectric.org/

This will allow you to test sqllite operation from a junit point of view. Robolectric "emulate" the android environnment from your favorite jvm on your dev machine.

Typically, a test then looks like this :

@RunWith(GuiceRobolectricJUnitRunner.class)publicclassPhotoDatabaseTest {

    @Injectprivate Context context;

    @Injectprivate SharedPreferences sharedPreferences;

    @TestpublicvoiddataInsertBaseTest()throws SQLException {
        PhotosUploadDataSourcephotosUploadDataSource=newPhotosUploadDataSource(context);
        photosUploadDataSource.deleteAll();

        MediaItemmediaItem=newMediaItem();
        mediaItem.setLocation("/test/");
        mediaItem.setName("photo.jpg");
        mediaItem.setSize(5496849);
        mediaItem.setStatus(MediaItem.STATUS_PENDING);
        mediaItem.setType("images/jpg");
        MediaItemresultItem= photosUploadDataSource.createMediaItem(mediaItem);
        assertNotNull(resultItem);
        Utils.displayObject(resultItem);
    }
  } 

GuiceRobolectricJUnitRunner is your typical test runner junit thing (here with guice but you can do it without it). One of the interesting thing is that you can simulate all kind of interesting behaviors as your database does not persist between tests (or you can by implementing a pre population in a @beforeTest). More here : http://robolectric.org/customizing.html

Post a Comment for "How To Test Android Sqlite With Junit?"