Exit course
Chapter 2 of 10 Intermediate 6 min read 2 quick checks Updated

Gradle Setup and Your First Espresso Run

On this page
  1. Two kinds of tests in an Android module
  2. The Gradle files
  3. The first test
  4. Run it

Espresso tests are not a separate project. They live in your app's module, in their own source set, and Gradle builds and runs them. This chapter sets up that source set for the Espresso Shop app, explains every line that matters, and runs the first test on an emulator.

Two kinds of tests in an Android module#

A new Android module has two test folders, and they are easy to mix up:

Folder Runs on Typical content
src/test/ Your computer's JVM Plain unit tests: view models, parsers, business rules
src/androidTest/ An emulator or a device Instrumented tests: Espresso, UI Automator, database tests

Espresso needs a real Android runtime with real views, so every Espresso test goes in src/androidTest/. The layout of the sample project:

espresso-shop/
  settings.gradle.kts
  build.gradle.kts
  app/
    build.gradle.kts
    src/main/java/com/example/shop/        LoginActivity.kt, ProductsActivity.kt, ...
    src/main/res/layout/                   activity_login.xml, ...
    src/androidTest/java/com/example/shop/ LoginTest.kt, ProductListTest.kt, ...

Tests use the same package as the app (com.example.shop), so they can use the app's R.id constants and classes without imports.

The Gradle files#

The root build.gradle.kts declares the Android Gradle Plugin (AGP) version once:

plugins {
    id("com.android.application") version "9.5.1" apply false
}

AGP 9 compiles Kotlin by itself, so there is no separate org.jetbrains.kotlin.android plugin to add. (On AGP 8 and older you still apply that plugin next to com.android.application; nothing else in this course changes.) The settings.gradle.kts needs the google() and mavenCentral() repositories for plugins and dependencies, which every Android Studio template already has.

The module's app/build.gradle.kts:

plugins {
    id("com.android.application")
}

android {
    namespace = "com.example.shop"
    compileSdk = 36

    defaultConfig {
        applicationId = "com.example.shop"
        minSdk = 24
        targetSdk = 36
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    testOptions {
        animationsDisabled = true
    }
}

dependencies {
    implementation("androidx.appcompat:appcompat:1.7.1")
    implementation("androidx.recyclerview:recyclerview:1.4.0")

    androidTestImplementation("androidx.test.ext:junit-ktx:1.3.0")
    androidTestImplementation("androidx.test:runner:1.7.0")
    androidTestImplementation("androidx.test:rules:1.7.0")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
}

What each test line does:

  • testInstrumentationRunner names the class that starts your tests on the device. AndroidJUnitRunner is the standard one: it launches the app process, finds every JUnit 4 test class in the test APK and runs it. You only change this if you write a custom runner, for example one that swaps the Application class for a test version.
  • animationsDisabled = true turns off window, transition and animator animations while Gradle runs the tests. Espresso does not wait for animations to finish, so an animation that is still running when a check happens is a classic source of flaky failures. Google's testing guide recommends turning them off on test devices.
  • androidTestImplementation dependencies only go into the test APK, never into the app you ship.
  • espresso-core is Espresso itself: onView, the matchers, actions and assertions.
  • runner and rules provide AndroidJUnitRunner and JUnit rules for the instrumentation.
  • junit-ktx provides AndroidJUnit4 and ActivityScenarioRule, which starts an activity before each test and closes it after.

Later chapters add espresso-contrib (lists), espresso-intents (intents), espresso-idling-resource (synchronisation) and the Test Orchestrator. The versions above were the current stable AndroidX Test releases in November 2026; Android Studio's dependency hints will tell you when newer ones appear.

A colleague adds espresso-core with implementation(...) instead of androidTestImplementation(...). The tests still run. What is wrong?

implementation puts a library into the app APK itself. Test-only libraries belong in androidTestImplementation, which only reaches the test APK. Where a test lives (src/test or src/androidTest) decides JVM or device, not the dependency configuration.

The first test#

The login screen has two text fields, a button and an error label. Its layout uses ordinary ids:

<EditText android:id="@+id/username" ... />
<EditText android:id="@+id/password" android:inputType="textPassword" ... />
<Button android:id="@+id/login" android:text="Log in" ... />
<TextView android:id="@+id/error" ... />

A first test only checks that the screen shows what it should, which is a good way to prove the setup before writing anything clever. Create app/src/androidTest/java/com/example/shop/LoginScreenTest.kt:

package com.example.shop

import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class LoginScreenTest {

    @get:Rule
    val activityRule = ActivityScenarioRule(LoginActivity::class.java)

    @Test
    fun showsTheLoginForm() {
        onView(withId(R.id.username)).check(matches(isDisplayed()))
        onView(withId(R.id.login)).check(matches(withText("Log in")))
    }
}

Three things to notice:

  • @RunWith(AndroidJUnit4::class) marks the class as an instrumented JUnit 4 test.
  • @get:Rule is the Kotlin way to expose a JUnit rule: the get: target puts the annotation on the property's getter, which is where JUnit looks. Writing @Rule alone compiles, and then JUnit fails at run time with an error that the rule must be public.
  • ActivityScenarioRule launches LoginActivity fresh before each test method and finishes it afterwards, so every test starts on the login screen.

Run it#

Start an emulator from Android Studio's Device Manager, or from the command line (emulator -avd <name>), and check that adb devices lists it. Then run every instrumented test in the module:

./gradlew connectedDebugAndroidTest

Gradle builds the app APK and the test APK, installs both, runs the tests and uninstalls them again:

> Task :app:connectedDebugAndroidTest
Running tests on devices: Medium_Phone_API_35(AVD) - 15

BUILD SUCCESSFUL in 1m 17s

Results land in two places: an HTML report at app/build/reports/androidTests/connected/debug/index.html and JUnit XML files under app/build/outputs/androidTest-results/connected/debug/. When a test fails, Gradle prints the path to the HTML report, which has the full Espresso error, including a dump of the view hierarchy.

In Android Studio you can also click the green run arrow next to a test class or method. It runs the same instrumentation and shows the results in the Run window, which is the quickest loop while you write a test.

To run a single class from the command line, pass an instrumentation argument through Gradle:

./gradlew connectedDebugAndroidTest \
  -Pandroid.testInstrumentationRunnerArguments.class=com.example.shop.LoginScreenTest

A test passes when you run it alone and fails in the full run with "expected 'Log in'" while a screen transition is still sliding in. What is the first thing to check?

Espresso waits for the main thread, not for animations. A transition still in progress when the check runs is a textbook animation flake; animationsDisabled = true (or turning off the three animation scales in developer options) removes it.

With the setup proven, the next chapter writes tests that actually do something: type, tap and check results.