Last active
January 28, 2022 17:08
-
-
Save hardik-trivedi/ba78bfd1b8b539aaf93307083d1a01bf to your computer and use it in GitHub Desktop.
This drawable matcher helps you to assert that ImageView has specific drawable set. This is to be used in Espresso test cases for your Android app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Credit https://github.com/dbottillo/Blog/blob/espresso_match_imageview/app/src/androidTest/java/com/danielebottillo/blog/config/DrawableMatcher.java | |
* Original Author: https://github.com/dbottillo | |
* Converted to Kotlin by Hardik Trivedi | |
*/ | |
class DrawableMatcher internal constructor(private val expectedId: Int) : | |
TypeSafeMatcher<View>(View::class.java) { | |
private var resourceName: String? = null | |
override fun matchesSafely(target: View): Boolean { | |
if (target !is ImageView) { | |
return false | |
} | |
if (expectedId == EMPTY) { | |
return target.drawable == null | |
} | |
if (expectedId == ANY) { | |
return target.drawable != null | |
} | |
val resources = target.getContext().resources | |
val expectedDrawable = ContextCompat.getDrawable(target.getContext(), expectedId) | |
resourceName = resources.getResourceEntryName(expectedId) | |
if (expectedDrawable == null) { | |
return false | |
} | |
val bitmap = getBitmap(target.drawable) | |
val otherBitmap = getBitmap(expectedDrawable) | |
return bitmap.sameAs(otherBitmap) | |
} | |
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.draw(canvas) | |
return bitmap | |
} | |
override fun describeTo(description: Description) { | |
description.appendText("with drawable from resource id: ") | |
description.appendValue(expectedId) | |
if (resourceName != null) { | |
description.appendText("[") | |
description.appendText(resourceName) | |
description.appendText("]") | |
} | |
} | |
companion object { | |
internal val EMPTY = -1 | |
internal val ANY = -2 | |
} | |
} | |
// Using DrawableMatcher | |
fun withDrawable(@DrawableRes resourceId: Int): Matcher<View> { | |
return DrawableMatcher(resourceId) | |
} | |
onView(withId(R.id.ID_OF_YOUR_IMAGEVIEW)).check(matches(withDrawable(R.drawable.YOUR_DRAWABLE_RES_NAME))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment