Robolectric: An Introduction

Sunday, 30 November 2014 13:13

Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds.

With Robolectric you can write tests like this:

public class LogoutTest {
    private Activity activity;
    private Button pressExitButton;
    private TextView result;
    public void setUp() throws Exception {
        activity = new MyActivity();
        pressExitButton = (Button) activity.findViewById(;
        result = (TextView) activity.findViewById(;
    public void logout() throws Exception {
        String resultText = result.getText().toString();
        assertThat(resultText, equalTo(“Login Screen”));

Robolectric makes this possible by intercepting the loading of the Android classes and rewriting the method bodies. Robolectric re-defines Android methods so they return null (or 0, false, etc.), or if provided Robolectric will forward method calls to shadow Android objects giving the Android SDK behavior. Robolectric provides a large number of shadow objects covering much of what a typical application would need to test-drive the business logic and functionality of your application.


Item tags