Screenshot testing
Why it matters
- A padding change or a theme override can shift many screens at once; screenshot tests catch that in CI, while logic tests never see it.
- Interviewers ask which tool you chose (Roborazzi, Paparazzi, Compose Preview Screenshot Testing) and why, because they render in different ways and fit different setups.
- The popular tools render on the JVM without an emulator, so a screenshot suite can run as part of your local tests, not only on devices.
- Without a fixed rendering environment and deterministic UI state, screenshot tests become the flakiest suite in the repo and get switched off.
The simple explanation
- You photograph a shelf in your kitchen every morning and compare it with yesterday's photo.
- A tiny shift in lighting should not count as a change; a missing jar should.
- If you take today's photo with a different camera, everything looks "changed".
What is screenshot testing in Android? A screenshot test renders a piece of UI (a composable, a View or a whole screen) to an image and compares it with a stored reference image, also called a golden. If the difference is above a threshold, the test fails and the tool writes a diff image so you can see what changed. It catches visual regressions that unit tests and most UI tests miss.
Three widely used tools for Android:
| Tool | How it renders | Runs on | Test style |
|---|---|---|---|
| Roborazzi | Robolectric with native graphics | Local JVM tests | Any Robolectric test: Compose, Views, whole Activities |
| Paparazzi | Layoutlib (the renderer behind Android Studio previews) | Local JVM tests, no Robolectric | paparazzi.snapshot { } for composables, snapshot(view) for Views |
| Compose Preview Screenshot Testing | Layoutlib | Host-side, screenshotTest source set | @PreviewTest on @Preview composables |
Every tool has two modes:
- Record writes new reference images. Roborazzi:
./gradlew recordRoborazziDebug. Paparazzi:./gradlew recordPaparazziDebug. Compose Preview Screenshot Testing:./gradlew updateDebugScreenshotTest. - Verify renders again and fails on differences. Roborazzi:
verifyRoborazziDebug(orcompareRoborazziDebugto only write diff images). Paparazzi:verifyPaparazziDebug. Compose Preview Screenshot Testing:validateDebugScreenshotTest.
Compose Preview Screenshot Testing is Google's tool and is still experimental. Its standalone com.android.compose.screenshot plugin is no longer maintained; Google now points to running it through experimental AGP test suites in newer AGP versions, which use different task names. Check the current setup page before adopting it.
Rendering differences. Images rendered on macOS and Linux, or on the JVM and on a device, can differ slightly in text anti-aliasing and font metrics. Keep one renderer per set of goldens, record and verify in the same environment (many teams record in CI or in a pinned Docker image), and set a small difference threshold for leftover noise. Bundle the fonts your app uses instead of relying on system fonts.
Deterministic UI. Feed the composable fixed state (no real network, no current time, no random data). Compose tests run on a virtual clock, so the rule waits for finite animations to finish; to capture a specific frame, set mainClock.autoAdvance = false and step with mainClock.advanceTimeBy(...).
Notes
- Roborazzi and Paparazzi run as local tests on the JVM, so no emulator is needed. Compose Preview Screenshot Testing also runs host-side.
- Roborazzi needs Robolectric with
@GraphicsMode(GraphicsMode.Mode.NATIVE)on the test class andisIncludeAndroidResources = trueintestOptions.unitTests. - Roborazzi writes images to
build/outputs/roborazziby default; setroborazzi { outputDir.set(file("src/screenshots")) }so the goldens can be committed. - Paparazzi stores goldens in
src/test/snapshots; its docs suggest Git LFS for the PNGs. - Compose Preview Screenshot Testing uses
@PreviewTeston previews insrc/screenshotTest, and stores references insrc/screenshotTestDebug/referencewith the standalone plugin. - Each tool has a difference threshold:
maxPercentDifferencein Paparazzi,changeThresholdin Roborazzi'sRoborazziOptions.CompareOptions. Keep it small so real changes still fail. - Record and verify on the same OS and renderer. Goldens recorded on a Mac often fail on a Linux CI runner.
- Pin screen size and density, for example Robolectric
@Config(qualifiers = "w360dp-h640dp-xhdpi")or PaparazziDeviceConfig.PIXEL_5. Add dark mode and large font scale variants for important screens. - Screenshot tests do not verify behaviour. A button that looks right but calls the wrong function still passes; pair them with ViewModel and UI tests.
- Commit goldens with the code change, so a pull request shows the old and new image side by side for review.
Code example
A Roborazzi test that renders three states of a stateless UserCard composable on the JVM. Run ./gradlew recordRoborazziDebug once to write the goldens, and ./gradlew verifyRoborazziDebug in CI.
// build.gradle.kts (app): plugin id("io.github.takahirom.roborazzi"),
// testImplementation for roborazzi, roborazzi-compose, robolectric and ui-test-junit4, plus
// android { testOptions { unitTests { isIncludeAndroidResources = true } } }
// roborazzi { outputDir.set(file("src/screenshots")) }
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.takahirom.roborazzi.captureRoboImage
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(AndroidJUnit4::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(qualifiers = "w360dp-h640dp-xhdpi")
class UserCardScreenshotTest {
@get:Rule
val composeRule = createComposeRule()
@Test
fun online() {
composeRule.setContent {
AppTheme { UserCard(name = "Ada Lovelace", online = true) }
}
composeRule.onRoot().captureRoboImage()
}
@Test
fun offline() {
composeRule.setContent {
AppTheme { UserCard(name = "Ada Lovelace", online = false) }
}
composeRule.onRoot().captureRoboImage()
}
@Test
@Config(qualifiers = "+night")
fun longNameDarkMode() {
composeRule.setContent {
AppTheme { UserCard(name = "Augusta Ada King, Countess of Lovelace", online = true) }
}
composeRule.onRoot().captureRoboImage()
}
}captureRoboImage()does what the current Roborazzi mode says: in record mode it writes the PNG, in verify mode it compares with the stored image and fails on a difference, and in compare mode it writes a_compare.pngdiff image.@GraphicsMode(GraphicsMode.Mode.NATIVE)makes Robolectric draw with Android's native graphics, which Roborazzi needs to produce real images.@Config(qualifiers = "+night")adds night mode on top of the class qualifiers, so one class covers light and dark.- The composable gets plain values, no network image or current time, so every run draws the same pixels.
Run the idea in plain Kotlin
data class Pixel(val r: Int, val g: Int, val b: Int, val a: Int)
fun pixelDistanceSquared(a: Pixel, b: Pixel): Int {
val dr = a.r - b.r
val dg = a.g - b.g
val db = a.b - b.b
return dr * dr + dg * dg + db * db
}
fun compareScreenshots(
expected: Array<Pixel>,
actual: Array<Pixel>,
thresholdSquared: Int
): Pair<Boolean, Int> {
var mismatched = 0
for (i in expected.indices) {
if (pixelDistanceSquared(expected[i], actual[i]) > thresholdSquared) {
mismatched++
}
}
val total = expected.size
val ratio = mismatched.toDouble() / total.toDouble()
return Pair(ratio <= 0.01, mismatched)
}
fun main() {
val expected = arrayOf(
Pixel(255, 0, 0, 255),
Pixel(0, 255, 0, 255),
Pixel(0, 0, 255, 255),
Pixel(255, 255, 0, 255)
)
val minorShift = arrayOf(
Pixel(254, 1, 0, 255),
Pixel(0, 255, 1, 255),
Pixel(1, 0, 255, 255),
Pixel(255, 255, 1, 255)
)
val (pass1, mismatches1) = compareScreenshots(expected, minorShift, 25)
println("Minor shift: pass=" + pass1 + " mismatches=" + mismatches1 + "/4")
val broken = arrayOf(
Pixel(0, 0, 0, 255),
Pixel(0, 0, 0, 255),
Pixel(0, 0, 0, 255),
Pixel(0, 0, 0, 255)
)
val (pass2, mismatches2) = compareScreenshots(expected, broken, 25)
println("Visual regression: pass=" + pass2 + " mismatches=" + mismatches2 + "/4")
val same = arrayOf(
Pixel(255, 0, 0, 255),
Pixel(0, 255, 0, 255),
Pixel(0, 0, 255, 255),
Pixel(255, 255, 0, 255)
)
val (pass3, mismatches3) = compareScreenshots(expected, same, 25)
println("Identical: pass=" + pass3 + " mismatches=" + mismatches3 + "/4")
}Expected output:
Minor shift: pass=true mismatches=0/4
Visual regression: pass=false mismatches=4/4
Identical: pass=true mismatches=0/4
Small colour noise stays under the per-pixel tolerance, while a real change fails every pixel. Real tools work the same way with a per-image threshold.
In production
- Developers recorded reference images on their Macs and committed them.
- On the Linux CI runner, many screenshot tests failed on every pull request, with text shifted by a pixel or two and no layout change.
- Font rendering and anti-aliasing differ between the two operating systems, so the images never matched exactly.
- Added a CI workflow that records goldens on the same Linux image used for verification, and committed its output instead of laptop recordings.
- Bundled the app's fonts as resources so rendering no longer depended on system fonts.
- Set a small difference threshold for leftover anti-aliasing noise.
- The order summary screenshot failed at random: the "placed at" time changed every run, and a loading spinner was caught at a different angle each time.
- The test rendered the full screen with its real ViewModel, which read the system clock and started a load.
- Screenshot tests now render the stateless screen composable with a fixed
UiState, including a fixed timestamp. - The loading state is captured with
mainClock.autoAdvance = false, so the spinner is drawn at the same frame every time. - The ViewModel and its clock are covered by separate unit tests with an injected fake clock.
Common mistakes
- Recording on one OS and verifying on another. Text rendering differs between macOS, Linux and devices, so every screen with text "changes". Record and verify in the same environment.
- Mixing renderers for the same goldens. Device screenshots and JVM-rendered screenshots never match pixel for pixel. Pick one tool per set of goldens.
- Rendering live data. Real network images, the current time, or random IDs make every run different. Pass fixed state to a stateless composable.
- Forgetting native graphics in Roborazzi. Without
@GraphicsMode(GraphicsMode.Mode.NATIVE), Robolectric does not draw real pixels and the screenshots are useless. - A threshold so high it hides real changes. A large tolerance stops flakes but also lets a missing icon through. Fix the environment first; keep the threshold small.
- Screenshot-testing only the default theme. Dark mode, large font scale and small screens break layouts most often. Add variants for important screens.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is screenshot testing in Android and when would you add it?”
“How do you handle font and rendering differences between local machines and CI?”
“Roborazzi versus Paparazzi versus Compose Preview Screenshot Testing: how do you choose?”
“A screenshot test is flaky in CI but passes locally. How do you debug it?”
Quiz
What does captureRoboImage() do when you run ./gradlew verifyRoborazziDebug?
Why do screenshot tests recorded on a developer's Mac often fail on a Linux CI runner?
Which statement about Paparazzi is correct?
What is the best way to make a screenshot of an animated loading state deterministic in a Compose test?
0 of 4 answered
Mini task
Add a Roborazzi screenshot test to your project (15 min)
-
In the app module's
build.gradle.kts, add theio.github.takahirom.roborazziplugin andtestImplementationdependencies onroborazzi,roborazzi-compose,robolectricandandroidx.compose.ui:ui-test-junit4(use current versions from each project's releases page). SettestOptions { unitTests { isIncludeAndroidResources = true } }androborazzi { outputDir.set(file("src/screenshots")) }. -
Create
src/test/kotlin/.../MyCardScreenshotTest.ktwith@RunWith(AndroidJUnit4::class),@GraphicsMode(GraphicsMode.Mode.NATIVE)and@Config(qualifiers = "w360dp-h640dp-xhdpi"). -
Add
@get:Rule val composeRule = createComposeRule()and one@Testthat callscomposeRule.setContent { MyCard(...) }with fixed values, thencomposeRule.onRoot().captureRoboImage(). -
Run
./gradlew recordRoborazziDebugand confirm a PNG appears undersrc/screenshots/. -
Run
./gradlew verifyRoborazziDebugand confirm the test passes. -
Change one padding value in
MyCardby 4 dp, run step 5 again, and confirm it fails. Run./gradlew compareRoborazziDebugand open the_compare.pngimage it writes. -
Revert the change and confirm it passes again.
Done when: you have a passing screenshot test, a visible diff on a deliberate change, a clean pass after reverting, and the golden PNG committed to Git.