Jetpack Compose 测试:断言特定图像已设置

Phi*_*hil 20 android kotlin android-jetpack android-jetpack-compose

我有一个Image如下所示的组合:

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" },
)
Run Code Online (Sandbox Code Playgroud)

在仪器测试期间,我想确保设置了正确的绘图。我在类中没有找到任何东西可以实现这一点,例如SemanticsProperties编写自定义匹配器。有人可以帮忙吗?

Ris*_*hli 23

您可以自己添加语义。

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 }
)
Run Code Online (Sandbox Code Playgroud)

并测试它

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

composeRule.onNode(hasDrawable(R.drawable.my_drawable))
    .assertIsDisplayed()
Run Code Online (Sandbox Code Playgroud)


小智 -7

你可以用浓缩咖啡来做这个

 Espresso.onView(withId(R.drawable.testimage)).check(matches(isDisplayed()))
Run Code Online (Sandbox Code Playgroud)

https://developer.android.com/jetpack/compose/testing#espresso-interop

语义显然不知道显示什么图像。

  • 你不能使用 espresso 来断言可组合视图 (2认同)