Scala on Android

The comprehensive documentation

  • Information reliability Sustainable Won't become outdated
  • Last edit Fri Jul 10 19:44:32 2015 +0200
  • Edit on GitHub

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.

  • Information reliability Fragile Might become outdated very soon
  • Last edit Fri Jul 10 19:44:32 2015 +0200
  • Edit on GitHub

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.

  • Information reliability Fragile Might become outdated very soon
  • Last edit Sat Aug 29 13:39:41 2015 +0200
  • Edit on GitHub

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

Comments