All Articles

Robolectric 4: A quick introduction

Robolectric 4 introduced support for Espresso API. This support included the AndroidJunit test runner. It means that we can run the same test on the JVM , using robolectric test runner, or on the Android runtime (ART) using Android test runner.

In this blog, we will explore how to write tests that can easily run on the JVM and ART.

First, head to here to setup your project for Robolectric.

Project Structure

Standard Android projects have two folders for tests test & androidTest. Since the aim is to run the same test in either configuration. We will add sharedTest sources to both of them.

android {
...
sourceSets {
        androidTest {
            java.srcDirs += "src/sharedTest/java"
            kotlin.srcDirs += "src/sharedTest/java"
        }
        test {
            java.srcDirs += "src/sharedTest/java"
            kotlin.srcDirs += "src/sharedTest/java"
        }
}
...
}

This informs the build process that we have an additional folder called sharedTest that should be included in both test and androidTest sources.

Running a test

We will use Activity Scenario to write a test for an Activity. This activity has two TextViews, one has text and the second is invisible.

@RunWith(AndroidJUnit4::class)
class TextViewWithButtonActivityTest {

    private lateinit var activityScenario: ActivityScenario<TextViewWithButtonActivity>

    @Before
    fun setup() {
        activityScenario = ActivityScenario.launch(TextViewWithButtonActivity::class.java)
    }

    @Test
    fun checkFirstTextHasText() {
        onView(withId(R.id.first_text)).check(matches(withText("This is first text")))
    }

    @Test
    fun checkSecondTextIsInvisible() {
        onView(withId(R.id.second_text)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.INVISIBLE)))
    }
}

We can verify that this test runs on both the JVM and ART by running

./gradlew test

./gradlew connectedAndroidTest

or using Android studio.

Configuring Android Studio

Android studio tries to be helpful by automatically detecting the type of test. In this case, Android studio will always run it as Instrumentation test (on a device).

You will need to add an additional AndroidJUnit run configuration to customise how Android studio runs your test.


In part 2, we will see how Robolectric works, we will go through some issues you might find when using robolectric and see a workaround some common issues.