Day 32 of #100DaysOfCode

Exploring AndroidX for Testing

“Write once, run everywhere” tests in Android

Dhananjay Trivedi
Oct 19 · 4 min read
Pretty sure that's what the devs at Google had in mind when building AndroidX

Understanding Tests in Android

On Android, there are unit tests and instrumentation tests along with your actual code. That’s why you see three packages inside your main package.

Unit tests

Unit tests have a number of advantages:

  • Easy Setup: Frameworks like Mockito and Roboelectric are there to help you to write tests by mocking interactions with the Android framework to set up the state of the environment for the test.

Instrumentation Tests

Instrumentation tests have their own set of traits:

  • More Accurate: They are a lot more accurate, as they run on a device that is a lot closer to your end user’s experience, giving you greater confidence.
  • Less Support: However, not many APIs are available to set up preconditions for your tests.

How to Start Writing Tests in Android

You start with writing a failing UI test (make this one an instrumentation test) using Espresso. Next, you write some production code to make your failing UI test pass. To make the feature work, you write a series of unit tests, followed by your code to pass those unit tests.


AndroidX

AndroidX is a part of the Android Jetpack toolkit which is completely open-source, well-documented and consistent. It has four modules:

  1. Core: Consisting of ApplicationProvider (helps you get ApplicationContext quick and easy), ActivityScenario (APIs for testing your Activities), FragmentScenario (APIs for testing your Fragments)
  2. Espresso: ViewMatchers, ViewActions, Intents similar to the Espresso we have been using for UI testing.
  3. Truth: The Google OS testing assertion library. Helps you test Android Object, writing concise readable code. Contains IntentSubject, BundleSubject and ParcelableSubject.

Coolest AndroidX APIs

ApplicationProvider

ApplicationProvider gives context to your tests. Up to now, we had getContext() (for instrumentation tests) and getTargetContext() (for unit tests). If you are using getContext() in a unit test, you will get a runtime error which you will then have to put in additional time and effort to debug.

val context = getApplicationContext<Application>()

ActivityScenario

We all know about the Android Lifecycle; while testing, Activity Lifecycle can be a challenge for code testing, as during UI tests the activity state may change while your test might still be testing a different state of the activity.

@Test
fun testTheStateIsNullAtStart() {
// This code launches your activity
val activityScenario = launchActivity<ActivityName>()

// Ensures your activity stays in CREATED state
activityScenario.moveToState(Lifecycle.State.CREATED)

// You can inspect internal state of your activity by
activityScenario.onActivity { activity ->
assertThat(activity.variableName).isNull()
}
}
@Test
fun testActivityRecreation() {

// GIVEN
val username = "devDeejay"
val activityScenario = launchActivity<ActivityName>()
// WHEN
onView(withId(R.id.usernameEditText))
.perform(typeText(username))

activityScenario.recreate()
// THEN
onView(withId(R.id.usernameEditText))
.check(matches(withText(username)))
}

Intent Subject in Truth

By using Intent Subject, you can verify your intent values and if something goes wrong, it provides human-readable error messages.

@Test
fun testActivityIntent() {

// GIVEN
val username = "devDeejay"
val dataIntent = createIntent(username)
// THEN
assertThat(dataIntent).hasAction(ACTION_SEND)
assertThat(dataIntent).hasType("text/plain")
assertThat(dataIntent).extras()
.string(EXTRA_TEXT).isEqualTo(contactName)
}


Better Programming

Advice for programmers.

Dhananjay Trivedi

Written by

Gonna leave you better than I found you. Full Stack Android Engineer @ Softway.

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade