Fork me on GitHub

Robolectric

Getting Started

RobolectricSample is a Maven-enabled sample app that shows how to layout your project, includes example tests, and a build.xml file for compiling and running tests.

Sample Tests

RobolectricSample’s own tests are an excellent source for sample test code. Of note:

Android IntelliJ Starter

Another resource, especially for IntelliJ users, is the Android IntelliJ Starter. This “template” project configures Robolectric as a git submodule.

Test Annotations

Robolectric must have an opportunity to intercept the class loading process of the Android classes to make this all work. This is done by adding the JUnit annotation to your tests. JUnit will defer processing of the Test file to the class defined in the @RunWith(RobolectricTestRunner.class) annotation. The RobolectricTestRunner.class sets up your test to run with Robolectric.

For example:

@RunWith(RobolectricTestRunner.class)  // <== REQUIRED for Robolectric! 
  public class HomeActivityTest {
    @Test
    public void shouldHaveAButtonThatSaysPressMe() throws Exception {
      // test code here
  }
}

Robolectric.shadowOf()

Sometimes Android classes don’t provide methods to access the state of the Android objects under test. The Robolectric.shadowOf() methods provide reference to the shadow instances representing Android objects, allowing tests to assert on state otherwise not available.

Suppose the application assigns a drawable resource id on an ImageView in layout xml, like this:

<ImageView
    android:id="@+id/pivotal_logo"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/pivotallabs_logo"
    android:layout_marginBottom="10dip"
    > 

Android provides no way to access the drawable resource id that was applied to the ImageView. Robolectric’s ShadowImageView object records the drawable resource id so you can assert on it in test, like this:

@Test
public void shouldHaveALogo() throws Exception {
    ImageView pivotalLogo = (ImageView) activity.findViewById(R.id.pivotal_logo);
    ShadowImageView shadowPivotalLogo = Robolectric.shadowOf(pivotalLogo);
    assertThat(shadowPivotalLogo.resourceId, equalTo(R.drawable.pivotallabs_logo));
}