Set up Robolectric with Android Studio

Introduction

Robolectric is a unit testing framework for Android, and it's a great choice because it

  • Supports Android SDK classes: Intent, Context, Activity ...
  • Tests are running in the developer's desktop JVM instead of an Android device.
  • Tests are fast, which is inevitable while using Test Driven Development.
  • In Android Studio (or IDEA), Robolectric test run as JUnit test with graphical support.

The most recent version of this library, Robolectric 3.0 offers out of the box Gradle and Android Studio support, and updated to Lollipop.

Requirements
  • Android Studio 1.1.0+, IDEA 14.1+
  • Gradle 1.1.0+
Including

We need to add Robolectric as a Gralde test dependency in the following way.

testCompile('org.robolectric:robolectric:3.0') {  
    exclude group: 'commons-logging', module: 'commons-logging'
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}

Please note that some packages may need to be excluded if it has been already included by other dependecies.

Usage

First, we create our test class. In the following example, we assume that there is a LoginActivity with a Button we would like to test. The test class itself has two important annotations, which used for test configuration. These annotations are only available since version 3.0 .

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class LoginActivityTest {

    LoginActivity_ loginActivity;

    @Before
    public void setup() throws Exception {
        // Calls the lifecycle: create-start-postCreate-resume
        loginActivity = Robolectric.setupActivity(LoginActivity_.class);
    }

    @Test
    public void testSignInButtonIsDisplayed() throws Exception {
        Assert.assertEquals(
                loginActivity.findViewById(R.id.login_sign_in_button).getVisibility(),
                View.VISIBLE);
    }
}

We create a Run Configuration, with Run - Edit configuration - Add JUnit test. Make sure that the Working directory and the Classpath point to the module we would like to test.

junit_run_config

Then, in the Build Variant window set the artifact to Unit Test.

roboelectric_build_variants

After the configuration is created, you can select and run like any other Android module. These tests are going to run on your JVM and the result are going to be presented with IDE integration.