Robolectric
Robolectric provides an implementation for the Android SDK for your local JVM installation. So instead of packaging up a testing *.apk
and deploying it to the device just to run the unit tests, you can instead execute the code on your development machine. This huge timesaver and popular tool is also available for Scala on Android users. You can even take this one step further and leverage the advanced features of ScalaTest instead of plain old junit.
Configuration
To enable unit testing with ScalaTest and Robolectric in your project, you need an additional library in your testing scope, called RoboTest. Expand your sbt configuration as follows.
libraryDependencies ++=
"com.geteit" %% "robotest" % "0.12" % "test" ::
"org.scalatest" %% "scalatest" % "2.2.5" % "test" ::
Nil
fork in Test := true
Please have a look at the RoboTest RoboTest documentation for further configuration details.
Usage
Place your unit tests in the ./src/test/scala
directory. All test classes may be equipped with an @Config
annotation for Robolectric. The annotation allows you to manually specify the AndroidManifest.xml
file location or Android SDK version to use for text execution.
Below is a fully functional test case taken from the Hello Scala! repository.
package com.example.test
import android.os.Build.VERSION_CODES.LOLLIPOP
import com.example.R
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.scalatest.{Matchers, FlatSpec, FeatureSpec, RobolectricSuite}
@Config( sdk = Array( LOLLIPOP ) )
class Test
extends FlatSpec
with Matchers
with RobolectricSuite {
"Resources" should "be accessible via R" in {
RuntimeEnvironment.application.getString( R.string.name ) shouldBe "Hello Scala!"
}
}
Further reading
- Robolectric
Official project page
- RoboTest
GitHub project page
- Hello Scala!
GitHub repository that serves as Scala on Android project starter template
- Android SDK Plugin for SBT samples
Sample projects on GitHub