The Test-Infected Programmer's
Android Apothecary

 

Nik Haldimann / @nikhaldi

Confession Time

  • I'm not an experienced Android developer
  • I'm test-infected

Symptoms: Slow tests

Diagnosis: Emulatoritis

Remedy: Robolectric

Robolectric

Write Android unit tests in plain old JUnit 4
and run them on a plain old JVM

http://pivotal.github.io/robolectric/


@RunWith(RobolectricTestRunner.class)
public class HelloWorldActivityTest {
    private Activity activity;

    @Before
    public void setUp() throws Exception {
        activity = new HelloWorldActivity();
        activity.onCreate(null);
    }

    @Test
    public void displaysHelloWorld() throws Exception {
        TextView helloWorld =
            (TextView) activity.findViewById(R.id.hello_world);
        assertEquals("Hello World", helloWorld.getText());
    }
}
		

Caution

Robolectric replaces Android SDK stub implementations with "shadows" at class-load time

Symptoms: Long, unreadable blocks of assertions

Diagnosis: Degenerative Assertion Tract

Remedy: FEST Android

Fluent Assertions


import static org.fest.assertions.Assertions.assertThat;

List<String> androids = ...;

assertThat(androids)
    .hasSize(4)
    .contains("Deckard", "Batty")
    .excludes("Holden");

assertThat("Data").isIn(androids);
		

FEST Android

http://square.github.io/fest-android/


// Regular FEST
LinearLayout layout = ...;
assertThat(layout.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(layout.getChildCount()).isEqualTo(4);
			

// FEST Android
import static org.fest.assertions.api.ANDROID.assertThat;

assertThat(layout)
    .isVisible()
    .hasChildCount(4);
			

Symptoms: Can't find relevant views in a complex UI

Diagnosis: Rampant Views Syndrome

Remedy: ViewSelector

ViewSelector

https://github.com/nikhaldi/android-view-selector

Find views with CSS selectors
and make assertions about them

ViewSelector Examples


import static com.nikhaldimann.viewselector.
    ViewSelectorAssertions.assertThat;
import static com.nikhaldimann.viewselector.
    ViewSelectorAssertions.selection;

assertThat(selection("TextView", activity))
    .hasSize(5);
	

assertThat(selection("TextView[tag=important]", activity))
    .hasSize(1);
	

assertThat(selection("#container ImageView", activity))
    .hasAttributeEqualTo("width", 100);
	

assertThat(selection("LinearLayout#groceries > TextView", activity))
    .hasAttributesEqualTo("text", "milk", "cereal");
	

Thanks for listening!