获取要测试的android视图的背景色

问题描述 投票:0回答:1

我正在使用Espresso创建Android Instrumented测试,我想测试视图的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"
/>

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

android android-espresso android-testing android-color
1个回答
0
投票

我相信随着测试的通过,我找到了解决该问题的方法,但是我不知道这是否是最好的方法。我注意到从ImageView获取backgroundTintList时,它包含表示颜色的整数数组。我可以用它来测试颜色(科特琳):

// 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))
© www.soinside.com 2019 - 2024. All rights reserved.