Jetpack Compose Testing: Assert specific image is set

Viewed 1255

I have an Image in compose like the following:

Image(
    bitmap = ImageBitmap.imageResource(id = R.drawable.testimage),
    contentDescription = null, // Only decorative image
    contentScale = ContentScale.FillWidth,
    modifier = Modifier
        .requiredHeightIn(max = 250.dp)
        .fillMaxWidth()
        .semantics { testTag = "MyTestTag" },
)

During an Instrumentation test I want to make sure the correct drawable is set. I did not find anything to achieve this in classes like SemanticsProperties to write a custom matcher. Can anyone help?

3 Answers

You can add a semantic yourself.

val DrawableId = SemanticsPropertyKey<Int>("DrawableResId")
var SemanticsPropertyReceiver.drawableId by DrawableId

val resId = R.drawable.my_drawable
Image(
    painter = painterResource(id = resId),
    contentDescription = null,
    Modifier.semantics { drawableId = resId }
)

And test it with

fun hasDrawable(@DrawableRes id: Int): SemanticsMatcher =
    SemanticsMatcher.expectValue(DrawableId, id)

composeRule.onNode(hasDrawable(R.drawable.my_drawable))
    .assertIsDisplayed()

If you prefer to keep things simple and avoid defining your own semantics, use the testTag:

val resId = R.drawable.some_image
Image(
    painter = painterResource(id = resId),
    contentDescription = null,
    Modifier.testTag = resId.toString()
)

and in your test:

composeTestRule.onNodeWithTag(R.drawable.someImage.toString())
    .assertIsDisplayed()
Related