2 min readApr 22, 2021
Many time we want to check if a Icon or Image is in a ImageView is same as we want to show using Espresso

You can do so with the help of a custom Matcher.
In your test class case:
// Checks View with Correct Icon is Visible
private fun checkIconIsShown(imageIcon: Int) {
onView(
Matchers.allOf(
isDescendantOfA(withId(R.id.user_profile)),
withId(R.id.user_avatar),
DrawableMatcher(imageIcon))
).check(ViewAssertions.matches(isDisplayed()))
}
In Matcher Class you basically compare Bitmap for the drawable you want to test with the Bitmap from Drawable from ImageView you want to test. So basically we compare Images BitMap generated from 2 sources and expect them to be same

/**
* Matches Drawable in ImageView is Same as expectedImageResource Image Resource Provided
*/
class DrawableMatcher(private val expectedImageResource: Int) : TypeSafeMatcher<View>(View::class.java) {
override fun matchesSafely(targetImageView: View): Boolean {
if (targetImageView !is ImageView) {
return false
}
if (expectedImageResource < 0) {
return targetImageView.drawable == null
}
val expectedDrawable = ContextCompat
.getDrawable(targetImageView.getContext(),
expectedImageResource)
?: return false
val bitmap = getBitmap(targetImageView.drawable)
val otherBitmap = getBitmap(expectedDrawable)
return compareBitMap(bitmap, otherBitmap)
}
private fun compareBitMap(bitmap: Bitmap, otherBitmap: Bitmap): Boolean {
val bitMapAreSame = bitmap.sameAs(otherBitmap) &&
(bitmap.width == otherBitmap.width &&
bitmap.width == otherBitmap.width &&
bitmap.height == otherBitmap.height &&
bitmap.byteCount == otherBitmap.byteCount &&
bitmap.density == otherBitmap.density)
bitmap.recycle()
otherBitmap.recycle()
return bitMapAreSame
}
private fun getBitmap(drawable: Drawable): Bitmap {
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth,
drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.setTint(Color.TRANSPARENT)
drawable.draw(canvas)
return bitmap
}
override fun describeTo(description: Description) {}
}
That’s all folks Happy Testing
