Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose Testing: Assert specific image is set

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?

like image 307
Phil Avatar asked Nov 17 '25 03:11

Phil


1 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()
like image 143
Rish K Avatar answered Nov 18 '25 20:11

Rish K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!