Jetpack Compose - screenshot test fails with NoClassDefFoundError after captureToImage()

274 views Asked by At

Running the following test that takes screenshot of a composable results in NoClassDefFoundError

Test:

@RunWith(AndroidJUnit4::class)
class MyTest {
    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun exampleTest() {
        composeTestRule.setContent {
            MyComposable()
        }

        composeTestRule.onRoot().captureToImage()
    }
}

Stack trace:

java.lang.NoClassDefFoundError: androidx.compose.ui.test.android.WindowCapture_androidKt$$ExternalSyntheticLambda0
at androidx.compose.ui.test.android.WindowCapture_androidKt.generateBitmapFromPixelCopy(WindowCapture.android.kt:112)
at androidx.compose.ui.test.android.WindowCapture_androidKt.generateBitmap(WindowCapture.android.kt:104)
at androidx.compose.ui.test.android.WindowCapture_androidKt.access$generateBitmap(WindowCapture.android.kt:1)
at androidx.compose.ui.test.android.WindowCapture_androidKt$captureRegionToImage$1.invoke(WindowCapture.android.kt:50)
at androidx.compose.ui.test.android.WindowCapture_androidKt$captureRegionToImage$1.invoke(WindowCapture.android.kt:46)
at androidx.compose.ui.test.android.WindowCapture_androidKt.withDrawingEnabled(WindowCapture.android.kt:60)
at androidx.compose.ui.test.android.WindowCapture_androidKt.captureRegionToImage(WindowCapture.android.kt:46)
at androidx.compose.ui.test.AndroidImageHelpers_androidKt.processSingleWindowScreenshot(AndroidImageHelpers.android.kt:138)
at androidx.compose.ui.test.AndroidImageHelpers_androidKt.captureToImage(AndroidImageHelpers.android.kt:75)
at androidx.compose.ui.test.AndroidImageHelpers_androidKt.captureToImage(AndroidImageHelpers.android.kt:50)
at com.example.MyTest.exampleTest(MyTest.kt:47)
1

There are 1 answers

0
Sergei Kozelko On

captureToImage is only available on API 26+ and will fail with NoClassDefFoundError when run on lower API devices.

You can catch this error by enabling lint in test sources with android { lintOptions { checkTestSources true } }.

Also you can run the test only on API 26+ devices by annotating it with @SdkSuppress(minSdkVersion = 26). In that case lint won't give any errors either.