Waldo sessions now support scripting! – Learn more
Testing

A Guide to Getting Started With AndroidX Test

Pius Aboyi
Pius Aboyi
A Guide to Getting Started With AndroidX Test
December 20, 2022
5
min read

AndroidX Test is a set of Jetpack libraries that focus on testing. Within AndroidX Test, you'll find different tools, like JUnit and Espresso, for performing tests like unit tests, end-to-end tests, and more. 

The beauty of Jetpack (or AndroidX) is that it brings related tools built by Google into one place, making it easier to use such tools and follow best practices. In the past, some of the tools in AndroidX were either independent or part of the old Android support libraries. The support libraries existed to improve compatibility across different Android versions and API levels. However, over time, as things evolved, issues like confusing multiple versions of the Android support libraries led to the creation of Jetpack. 

In this post, you'll learn how to use the AndroidX Test libraries to write and run different tests for your Android app

"The beauty of Jetpack (or AndroidX) is that it brings related tools built by Google into one place"

Examples of AndroidX Test Libraries and Their Benefits

Before we go into the actual tutorial on how to use the AndroidX Test libraries, let's discuss some of the most common libraries that make up AndroidX Test. 

1. AndroidX Test Core

As the name says, this component of AndroidX Test contains the core tools. Two of those tools are ActivityScenario, which helps start an activity, and ApplicationProvider, which provides context for the app you're testing. 

Benefits

1. It provides an API for starting an activity. 

2. This library makes it possible to get the context of the app you're testing so you can use the context in the rest of your test. 

2. AndroidX Test Junit

This library provides APIs and a JUnit4 runner to run JUnit4 tests in Android. The JUnit4 runner initiates the test class you want to run. In order to use the JUnit4 runner, you need to annotate your test class with @RunWith(AndroidJUnit4::class)

Benefit

1. It provides JUnit4 APIs and a runner for Android. 

3. AndroidX Test Truth

Truth is an assertion library. A key part of writing tests is validating that the data or element under test meets some expected outcome. You can do this type of validation using an assertion library. 

Benefit

1. It provides a means for doing assertions. 

4. AndroidX Test Espresso

Espresso is a UI testing framework that makes it easier to write automated end-to-end tests for your Android app. 

Benefits

1. Espresso provides easy-to-use APIs for writing UI tests. 

2. Using the onView() method, you can easily locate a view by its property, like its ID. 

3. Espresso also provides methods for interactions like clicking on a view. 

How to Use AndroidX Test

Now that you know what the AndroidX Test library is, let's walk through a tutorial on how to use some of the tools and frameworks in it. 

Step 1: Add Dependencies

In order to use any of the AndroidX Test libraries, you first need to include the correct dependencies for the library in your project. For this example, we'll add AndroidX Test to a basic Android Studio project. 

Open the app-level build.gradle file and add the following code to the dependencies section: 


dependencies {
    androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.4'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test:runner:1.5.1'
    androidTestImplementation'androidx.test.ext:truth:1.5.0'

    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.5.0'
}

Step 2: Create a New Activity Class

Let's create a new activity class so that we can explore the ActivityScenario feature. 

To do that, right-click on the package name for your application in the same directory where you have MainActivity, then select New > Activity > Empty Activity. You can name this new activity SecondActivity

Add the following views to the layout XML file using the IDs provided below: 

1. EditText, ID: name_edit_text 

2. Button, ID: submit_button 

3. TextView, ID: name_tv 

Next, open the SecondActivity.kt file and add the following code to the onCreate() method, just after the line with setContentView()


val nameEditText:EditText = findViewById(R.id.name_edit_text)
val submit:Button = findViewById(R.id.submit_button)

val nameTv:TextView = findViewById(R.id.name_tv)

submit.setOnClickListener {
    nameTv.text = nameEditText.text.toString()
}

Before we continue, let's walk through what we did with the above code. 

First, we initialized variables that hold references to our three views. Next, we set onClickListener such that once the user clicks on the submit button, the listener writes the current value in the EditText to nameTv

Here's the full code for SecondActivity.kt


class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second2)

        val nameEditText:EditText = findViewById(R.id.name_edit_text)
        val submit:Button = findViewById(R.id.submit_button)

        val nameTv:TextView = findViewById(R.id.name_tv)

        submit.setOnClickListener {
            nameTv.text = nameEditText.text.toString()
        }
    }


}

 

image shows a person holding a computer mouse as they are navigating on the computer. There is a mechanical keyboard as the main focus.

Step 3: Write a UI Test

In this step, we'll write a simple test that starts SecondActivity and types some text into the EditText. The test uses Espresso to perform the interaction. Next, we'll verify that the text entered matches a specific expected string. 

Go to the AndroidTest folder in your project and create a new Kotlin class. Name the class SecondActivityTest.

Then open the SecondActivityTest class file and add the @RunWith(AndroidJUnit4::class) annotation before the class declaration. 

After that, add the following code inside the class: 


@get:Rule var activityScenarioRule = activityScenarioRule<SecondActivity>()


@Test
fun nameEntered() {
    // WHEN
    onView(withId(R.id.name_edit_text)).perform(typeText("John"))
    onView(withId(R.id.submit_button)).perform(click())
    // THEN
    onView(withId(R.id.name_tv)).check(ViewAssertions.matches(ViewMatchers.withText("John")))

}

Just like in the previous step, let's walk through what the above code does. 

First, we created a new ActivityScenario rule to launch the SecondActivity screen. This used the AndroidX Test Core library. 

Next, we used Espresso's onView() method to locate EditText and type in the name "John." Again, using onView(), we located the button and performed a click action. Finally, we verified whether the text from the name_tv TextView is an exact match to "John." 

The following shows the full code of SecondActivityTest


@RunWith(AndroidJUnit4::class)
class SecondActivityTest {

    @get:Rule
    var activityScenarioRule = activityScenarioRule<SecondActivity>()
    @Test
    fun nameEntered() {

        // WHEN
        onView(withId(R.id.name_edit_text)).perform(typeText("John"))

        onView(withId(R.id.submit_button)).perform(click())
        // THEN
        assertThat(getActivity().findViewById(R.id.name_tv)).equals("John")
    }
}

Step 4: Run the Tests

To run the test, open the SecondActivityTest file and click on the green Play button next to the class declaration. Then, wait for the project to build and the app to start running on your device or emulator. 

Once the app is up and running, you should observe Espresso performing the action of typing and clicking the button automatically. To determine whether the test passed or failed, see the test report in Android Studio. The test passes if the name entered matches the expectation we specified using the Truth library.

Performing More Tests

Outside of using AndroidX Test, there are other ways for testing your application including manual testing. However, manual testing can be slow and the likeliness of human error is high. 

Summing Up

AndroidX Test unifies several testing frameworks for Android development. Within AndroidX Test, you can find tools for running your tests, performing UI automation, doing assertions and much more. For the sake of this tutorial, we discussed four libraries under AndroidX Test, which included AndroidX Test Core, JUnit, Truth, and Espresso. We also walked through an example of how to use AndroidX Test which used all four libraries.

You can test your application in other ways, without using AndroidX Test, with, for example, manual testing. However, manual testing can be slow and the likeliness of human error is high. 

If you want to perform automated testing with less configuration and without having to write test scripts, you can try a tool like Waldo. Waldo offers a no-code testing solution for mobile applications.

Automated E2E tests for your mobile app

Waldo provides the best-in-class runtime for all your mobile testing needs.
Get true E2E testing in minutes, not months.

Reproduce, capture, and share bugs fast!

Waldo Sessions helps mobile teams reproduce bugs, while compiling detailed bug reports in real time.