获取 android 视图的背景色调以进行测试

Get background tint of an android View for testing

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

<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))