yandex

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:

@RunWith(RobolectricTestRunner.class)
public class LogoutTest {
    private Activity activity;
    private Button pressExitButton;
    private TextView result;
    @Before
    public void setUp() throws Exception {
        activity = new MyActivity();
        activity.onCreate(null);
        pressExitButton = (Button) activity.findViewById(R.id.exit_button);
        result = (TextView) activity.findViewById(R.id.result);
    }
    @Test
    public void logout() throws Exception {
        pressExitButton.performClick();
        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.

IntexSoft is in the Clutch Top 10 of Belarusian Web & Software Developers More