View screenshots taken during an Espresso test in Android Studio


I have a few Espresso UI tests for my Android app. During the tests, there are some moments where I take screenshots, which will be evaluated after the test, qualitatively.

I found the androidx.test.espresso.screenshot.captureToBitmap method, as well as the SemanticsNodeInteraction.captureToImage() method for use with Jetpack Compose.

However, both of these return the captured screenshot as their return value, so it is my job to save the screenshot so I can view it later.

I have successfully used this answer to save the screenshots to the phone's storage, but the "Files" app on my phone is a bit inconvenient to use.

I would much prefer having the screenshots sent to the computer that is running Android Studio, or even have them show up in Android Studio itself, if that is possible.

How can I do this?

0
Feb 3 at 3:18 AM
User AvatarSweeper
#android#kotlin#android-studio#android-espresso

Accepted Answer

How to save Espresso / Compose screenshots and view them on the host machine

Use AndroidX Test Storage instead of regular external storage.
Test Storage is designed for test artifacts (screenshots, logs, etc.) and allows Gradle / Android Studio to automatically pull files from the device after tests finish.


1. Enable Test Storage

Groovy

android {
    defaultConfig {
        testInstrumentationRunnerArguments useTestStorageService: 'true'
    }
}

dependencies {
    androidTestUtil 'androidx.test.services:test-services:1.4.2'
}

Kotlin DSL

android {
    defaultConfig {
        testInstrumentationRunnerArguments["useTestStorageService"] = "true"
    }
}

dependencies {
    androidTestUtil("androidx.test.services:test-services:1.4.2")
}

2. Capture and save screenshots

Espresso (Views)

onView(isRoot())
    .captureToBitmap()
    .writeToTestStorage("home_screen")

Jetpack Compose

composeTestRule.onRoot()
    .captureToImage()
    .asAndroidBitmap()
    .writeToTestStorage("compose_screen")

3. Run tests

Run via Gradle or Android Studio:

./gradlew connectedAndroidTest

4. Find screenshots on the host machine

After the test run completes, screenshots are automatically pulled from the device and stored under:

<module>/build/outputs/connected_android_test_additional_output/
    <variantAndroidTest>/connected/

(Exact variant folder name may differ.)


5. (Optional) Manual adb pull

Test Storage files live on the device at:

/storage/emulated/0/googletest/test_outputfiles

You can pull them manually if needed:

adb pull /storage/emulated/0/googletest/test_outputfiles

TL;DR

  • Use writeToTestStorage() to save screenshots

  • Enable useTestStorageService

  • Run connectedAndroidTest

  • Screenshots appear automatically in connected_android_test_additional_output

This is the recommended way to collect and view screenshots from Android instrumentation tests on the host machine.

User AvatarSarvenaz Mahmoudzadeh
Feb 3 at 12:48 PM
0