android - 获取用于测试的 android View 的背景色调

标签 android android-espresso android-testing android-color

我正在使用 Espresso 创建 Android Instrumented 测试,我想测试 View 的 backgroundTint 在特定操作后是否发生变化。我没有运气找到专门针对背景色调的类似问题。在这种情况下,它是一个使用圆形可绘制对象的 ImageView,并且颜色根据服务器连接从绿色变为红色。 View 正在通过 livedata 数据绑定(bind)更新

<ImageView
    android:id="@+id/connected_status"
    android:layout_width="10dp"
    android:layout_height="10dp"
    android:layout_gravity="end|top"
    android:background="@drawable/circle"
    android:backgroundTint="@{safeUnbox(viewModel.onlineStatus) ? @colorStateList/colorGreenMaterial : @colorStateList/colorRedPrimary}"
    android:contentDescription="@string/connection_indication"
/>

如何在 Instrumented 测试期间以编程方式获取 ImageView 的 backgroundTint 并检查其颜色?

最佳答案

我相信随着测试的进行,我找到了解决这个问题的方法,但是我不知道这是否是最好的解决方法。我注意到从 ImageView 获取 backgroundTintList 时它包含一个表示颜色的整数数组。我能够像这样使用它来测试颜色 (Kotlin):

// Get the integer value of the colors to test
val redColorInt = Color.parseColor(activityTestRule.activity.getString(R.color.colorRedPrimary))
var greenColorInt = Color.parseColor(activityTestRule.activity.getString(R.color.colorGreenMaterial))

// Add integers to a stateSet array
val stateSet = intArrayOf(redColorInt, greenColorInt)

// Get the view
val connectedStatus = activityTestRule.activity.findViewById<ImageView>(id.connected_status)

// Get the backgroundTintList
var tintList = connectedStatus.backgroundTintList

// Assert color, getColorForState returns 1 as default to fail the test if the correct color is not found
assertThat(tintList!!.getColorForState(stateSet, 1), `is`(redColorInt))

//Perform actions that change the background tint
...

// Get the updated backgroundTintList
tintList = connectedStatus.backgroundTintList

// Assert new color is now set
assertThat(tintList!!.getColorForState(stateSet, 1), `is`(greenColorInt))

关于android - 获取用于测试的 android View 的背景色调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470752/

相关文章:

android - 如何在开始 Espresso 测试之前准备数据库数据?

android - PerformException Error Performing Single Click Works with 5dp 边距

由于键盘启动弹出窗口,Android 仪器测试在 Google 的测试实验室 Galaxy S9+ 上失败

android - 如何测试 Galaxy S8 的 android.max_aspect

android - 当我运行我的 android UIAutomator 代码时,它显示错误

android - 在 Android 中显示一个透明的 Activity?

android - 如何在自定义微调项目之间添加空间?

android - Double Espresso 不适用于 Robolectric

android - 强制关闭ImageButton的onClick,无法弄清楚为什么

Android WebView 未加载 JavaScript 文件,但 Android 浏览器加载正常