I've been using Scala to create Android applications for some time now, and I've always been using ScalaTest for testing my Scala code. It felt perfectly natural that I wanted to test Android application the same way. When it comes to testing of Android applications, Robolectric is the main library for the job. Unfortunately it only comes with JUnit support, and using it from ScalaTest is only possible with some serious plumbing. Some time ago I decided to extract all this plumbing, update it to latest Robolectric release, and publish it as separate project: RoboTest.

Writing tests

To use Robolectric in your tests just add RobolectricSuite mixin to your test, make sure to add it as the last trait in class declaration.

class SampleRoboSpec extends FeatureSpec with RobolectricSuite {
  ...
}

It should be possible to use any testing style supported by ScalaTest, lifecycle traits like BeforAndAfter and BeforeAndAfterAll are also supported.

Here is sample test using shared database for all tests:

class DatabaseRoboSpec extends FeatureSpec 
    with Matchers with BeforeAndAfter with BeforeAndAfterAll with RobolectricSuite {

  var helper: SQLiteOpenHelper = _
  var db: SQLiteDatabase = _

  override protected def beforeAll(): Unit = {
    helper = new SQLiteOpenHelper(Robolectric.application, "test", null, 1) {
      override def onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int): Unit = {}
      override def onCreate(db: SQLiteDatabase): Unit = {}
    }
  }

  override protected def afterAll(): Unit = {
    Robolectric.application.getDatabasePath(helper.getDatabaseName).delete()
  }

  before {
    db = helper.getWritableDatabase
    db.execSQL("CREATE TABLE Test(_id INTEGER PRIMARY KEY, value TEXT);")
  }

  after {
    db.execSQL("DROP TABLE IF EXISTS Test;")
    db.close()
  }

  feature("Robolectric test using database") {

    scenario("Insert row") {
      val values = new ContentValues()
      values.put("_id", Integer.valueOf(1))
      values.put("value", "test")

      db.insert("Test", null, values) shouldEqual 1
    }

    scenario("Query all rows from empty table") {

      val cursor = db.query("Test", null, null, null, null, null, null)
      cursor.moveToFirst() shouldEqual false
      cursor.getCount shouldEqual 0
    }
  }
}

Checkout example project for complete setup and some other tests, also using AndroidManifest and resources.


blog comments powered by Disqus