Getting started with Test-Driven Development (TDD)

Note: This series is for advanced Android Developers. Are you a beginner? See our YouTube tutorials or other articles on this publication.

Most developers love to automate their work. Why test something for 30 minutes when it can take 10 seconds? As a developer, you need to ensure that your Android app is working 100% of the time. But testing the entire app after every code change can be difficult. That’s where Test-Driven Development comes into play. What is TDD?

TDD on YouTube.

TDD is a process for writing code that start with failed tests and ends with functional code. Here is an example test in Android Studio:


@Test
fun when_user_enters_first_and_last_name_check_to_confirm_that_message_is_correct() {
onView(withId(R.id.firstName)).perform(typeText("Jake"))
onView(withId(R.id.lastName)).perform(typeText("Smith"))
onView(withId(R.id.button)).perform(click())
onView(withId(R.id.message)).check(matches(withText("Welcome, Jake Smith!")))
}

Try reading the code above. Did any of it make sense? Even if you’ve never seen an Espresso test before, you may be able to understand keywords like R.id.firstName and perform and typeText. What does this Espresso test do?

First, it finds an EditText with the Id of firstName, then the test types “Jake” in that EditText. After a couple more lines, we check to see that the Id with message matches “Welcome, Jake Smith!”

For a complete walkthrough of the above code, see our YouTube video on Test-Driven Development.

Part two of this series will be available next Saturday at 8am.

About the author

Daniel Malone
Bringing more than a decade of software engineering experience, Daniel Malone is Editor at androidEveryday. An Austin native, Daniel is often found reading technical books, blogging and creating YouTube tutorials. When not working, he likes to listen to pop hits on Google Play Music.

Android RecyclerView Tutorial (Part 1)

  • Most apps contain lists of data using RecyclerView.
  • In this tutorial, use ConstraintLayout and Kotlin to display a list of data.

3 weeks ago

findViewById() in Kotlin

  • As you may have discovered, findViewByid() is no longer needed.
  • Kotlin adds the ability to directly access Views.

1 month ago

Android Architecture Components Tutorial: ViewModel + LiveData

  • Use Kotlin to build a basic Android app using Android Architecture Components.
  • As part of Jetpack, LiveData and ViewModel support a MVVM app architecture.

1 month ago