Android: Compelling reason to use Android Unit tests


About two years ago, in one of my senior classes, we were talking about unit tests and there was a classmate of mine who got into a great debate with the professor on the why we even needed them. During that time, I sided with my classmate, because I couldn’t see the point of it either and it seemed like a waste of effort to write a whole unit test to do this:

int sum  = 1 + 1
assertEquals(2, sum);

Looking back, the above test is certainly a lackluster example and I wished the professor had given us a more persuasive reason to use them.

Recently, I was working with a database and to test this database (e.g. making sure inserting a row inserted the values I expected) I was going to insert a row into my database, query the information, and spit out a log statement containing the values to confirm if they were correct. Afterwards, I would have to delete the inserted row to perform other tests. Sounds tedious right? Also testing like this is unreliable and also clutters up the production code makes everything really disorganized.

I did some research and found out that Android unit tests can help with that! It will create a new database instance, run the tests that you need and delete the database AUTOMATICALLY afterwards. So every test you run will have a new fresh database to use.

public void testQuery() {
   Cursor cursor = null;
   try {
      ContentValues values = new ContentValues();
      values.put(PersonEntry.COLUMN_FIRST_NAME, "Ellie");
      values.put(PersonEntry.COLUMN_LAST_NAME, "Van-Housen");

      // Insert mock data
      getMockContentResolver().insert(mUri, values);

      // Query the inserted data
      cursor = getMockContentResolver().query(

     if(cursor == null){
         fail("Cursor was null");

     } else{
             assertEquals("Ellie", cursor.getString(0));
             assertEquals("Van-Housen", cursor.getString(1));
       if(cursor != null){

Doing this, I would get a green light if tests were successful and a red light if test failed. The best part about this is that I can leave the tests here for other developers/coworkers to test themselves. I hope this will certainly convince you more than the “1 + 1” example.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s