Get background tint of an android View for testing


I am creating Android Instrumented tests using Espresso and I would like to test that the backgroundTint of a view changes after a certain action. I did not have any luck finding a similar question specifically for background tint. In this case it is an ImageView that uses a circle drawable and the color changes from green to red depending on server connection. The view is updating via livedata databinding

    android:backgroundTint"@{safeUnbox(viewModel.onlineStatus) ? @colorStateList/colorGreenMaterial : @colorStateList/colorRedPrimary}"

How can I programmatically get the backgroundTint of the ImageView during an Instrumented test and check its color?


I believe I found a solution to this problem as the test is passing, however I do not know if it is the best solution. I noticed when getting the backgroundTintList from the ImageView it contains an array of integers representing colors. I was able to use this to test the colors like so (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))

Answered By – James Pooley

Leave a Comment