Screenshot testing

Learn Android screenshot testing for Jetpack Compose with Roborazzi, Paparazzi or Compose Preview Screenshot Testing: record goldens, verify in CI, stop flakes. About 25 minutes.

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:

ToolHow it rendersRuns onTest style
RoborazziRobolectric with native graphicsLocal JVM testsAny Robolectric test: Compose, Views, whole Activities
PaparazziLayoutlib (the renderer behind Android Studio previews)Local JVM tests, no Robolectricpaparazzi.snapshot { } for composables, snapshot(view) for Views
Compose Preview Screenshot TestingLayoutlibHost-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 (or compareRoborazziDebug to 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 and isIncludeAndroidResources = true in testOptions.unitTests.
  • Roborazzi writes images to build/outputs/roborazzi by default; set roborazzi { 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 @PreviewTest on previews in src/screenshotTest, and stores references in src/screenshotTestDebug/reference with the standalone plugin.
  • Each tool has a difference threshold: maxPercentDifference in Paparazzi, changeThreshold in Roborazzi's RoborazziOptions.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 Paparazzi DeviceConfig.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.png diff 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

Goldens recorded on laptops fail on Linux CI
  • 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.
The fix
  • 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.
A screen that never looked the same twice
  • 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.
The fix
  • 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)

  1. In the app module's build.gradle.kts, add the io.github.takahirom.roborazzi plugin and testImplementation dependencies on roborazzi, roborazzi-compose, robolectric and androidx.compose.ui:ui-test-junit4 (use current versions from each project's releases page). Set testOptions { unitTests { isIncludeAndroidResources = true } } and roborazzi { outputDir.set(file("src/screenshots")) }.

  2. Create src/test/kotlin/.../MyCardScreenshotTest.kt with @RunWith(AndroidJUnit4::class), @GraphicsMode(GraphicsMode.Mode.NATIVE) and @Config(qualifiers = "w360dp-h640dp-xhdpi").

  3. Add @get:Rule val composeRule = createComposeRule() and one @Test that calls composeRule.setContent { MyCard(...) } with fixed values, then composeRule.onRoot().captureRoboImage().

  4. Run ./gradlew recordRoborazziDebug and confirm a PNG appears under src/screenshots/.

  5. Run ./gradlew verifyRoborazziDebug and confirm the test passes.

  6. Change one padding value in MyCard by 4 dp, run step 5 again, and confirm it fails. Run ./gradlew compareRoborazziDebug and open the _compare.png image it writes.

  7. 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.

Next: End-to-end tests and flakiness