Tuesday, June 11, 2013

Android: Unit Test for Custom Content Provider using Roboelectric

Robolectric provides a simple approach to automate unit test case for android by using standard JUnit tests. It runs on any JVM, without needing the emulator or a device.
Advantages of Roboelectric:
No Mocking Frameworks Required

Run Tests Outside of the Emulator

Test Annotations


To run your test with Robolectric, you need to tell JUnit using the @RunWith annotation on your test class:
@RunWith (RobolectricTestRunner.class) // required for Robolectric!
For more details: http://pivotal.github.io/robolectric/user-guide.html
With Robolectric, we can write a small unit test for custom content provide like this.

public class BookContentProviderTest {

 private Activity activity;
 private BookProvider bookProvider;
 private ContentResolver contentResolver;

 public static final String AUTHORITY = "com.test.provider.Book";

 public static final String BOOK_TABLE_NAME = "book";

  * The columns we are interested in from the database
 public static final String[] BOOK_PROJECTION = new String[] {
   BookColumns._ID, // 0
   BookColumns.BOOK_NAME, // 1

 public static final Uri BOOK_URI = Uri.parse("content://" + AUTHORITY + "/"

 private String[] bookList = new String[] { "angels and demons", "Book1",
   "Book2", "Book3" };

 public void setUp() throws Exception {
  bookProvider = new BookProvider();
  activity = new Activity();
  contentResolver = activity.getContentResolver();

  ShadowContentResolver.registerProvider(AUTHORITY, bookProvider);

 public void testContentProvider() {

  insertBook(new Book("53bfc0b980b0", "angels and demons"));
  insertBook(new Book("53bfc0b980b3", "Book1"));
  insertBook(new Book("53bfc0b980b1", "Book2"));
  insertBook(new Book("53bfc0b980b2", "Book3"));

  Cursor cursor = contentResolver.query(BOOK_URI, BOOK_PROJECTION, null,
    null, BookColumns.DEFAULT_SORT_ORDER);


  Assert.assertTrue(cursor.getCount() == 4);

  if (cursor.getCount() != 0) {
   do {
   } while (cursor.moveToNext());


 private void insertBook(Book book) {
  contentResolver.insert(BOOK_URI, getContentValue(book));

 private ContentValues getContentValue(Book book) {
  ContentValues values;
  values = new ContentValues();
  values.put(BookColumns._ID, book.getBookId());
  values.put(BookColumns.BOOK_NAME, book.getName());
  return values;


  1. Hey,guys,can you send me a sample project about this?thx.

    My email is duduhonngyao90@gmail.com

  2. Great


  3. Thanks for taking time to share this post. It is really useful. Continue sharing more like this.
    Android Training in Bangalore