Quick Start for Eclipse

Note: If you’re using Maven as your build tool you can include Robolectric tests in the same project as your application code without any additional configuration using the Android for Maven Eclipse plugin.

Download JARs

You’ll need at least the “robolectric-x.x.x-jar-with-dependencies” jar, which can be obtained here. You may also want the source jar matching your Robolectric version from the same location, in case you run in to any bugs. Also recommended, but not required, is the latest hamcrest-all jar.

Project Creation

Create a project

New Android Project dialog

Make sure to note the package name, as you’ll need it later. Target SDK can’t currently be set to anything higher than API 18, as Robolectric doesn’t yet support API 19.

Add a ‘test’ directory to your project

Add a ‘test’ subdirectory under libs

Finally, drag and drop/otherwise copy your test-related jar files (robolectric/sources/hamcrest) into the libs/test directory.

Create a JAVA project for your tests

Create and configure test Java project (not an Android Application Project)

Add dependency on the Android project

Add required libraries

Set classpath order

Click “Finish”, closing the new Java project dialog

Most of these settings can be changed later by right-clicking your test project, selecting “Build path” → “Configure Build Path”

Create a test Run Configuration

Your tests will not run without this step; Robolectric will not be able to locate your project resources.

Verify your setup

package com.example.myproject;

import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

public class MainActivityTest {

    MainActivity activity;

    public void setup()
        this.activity = Robolectric.buildActivity(MainActivity.class).create().get();

    public void shouldHaveHappySmiles() throws Exception 
        String hello = this.activity.getString(R.string.hello_world);
        assertThat(hello, equalTo("Hello world!"));

To run the tests

The tests may take quite a while to start running after the first launch. Robolectric downloads a real Android jar on the first run, placing it in your local maven repo. Future test runs are considerably faster.

If you get a RuntimeException saying: “no such layout layout/main”

It means that you have tried to run a test for which you do not have a Run Configuration set up. To remedy this: