Issue
I have my xml layout:
<EditText
android:id="@+id/passwordEditText"
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_marginBottom="20dp"
android:drawableStart="@drawable/ic_sign_in_password"
android:drawablePadding="15dp"
android:hint="@string/password"
android:textSize="15sp"/>
I want to write Espresso test check that EditText has
android:drawableStart="@drawable/ic_sign_in_password".
How I can do this?
Solution
Create a helper method sameBitmap
comparing 2 drawables.
private static boolean sameBitmap(Drawable actualDrawable, Drawable expectedDrawable) {
if (actualDrawable == null || expectedDrawable == null) {
return false;
}
if (actualDrawable instanceof StateListDrawable && expectedDrawable instanceof StateListDrawable) {
actualDrawable = actualDrawable.getCurrent();
expectedDrawable = expectedDrawable.getCurrent();
}
if (actualDrawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) actualDrawable).getBitmap();
Bitmap otherBitmap = ((BitmapDrawable) expectedDrawable).getBitmap();
return bitmap.sameAs(otherBitmap);
}
if (actualDrawable instanceof VectorDrawable ||
actualDrawable instanceof VectorDrawableCompat ||
actualDrawable instanceof GradientDrawable) {
Rect drawableRect = actualDrawable.getBounds();
Bitmap bitmap = Bitmap.createBitmap(drawableRect.width(), drawableRect.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
actualDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
actualDrawable.draw(canvas);
Bitmap otherBitmap = Bitmap.createBitmap(drawableRect.width(), drawableRect.height(), Bitmap.Config.ARGB_8888);
Canvas otherCanvas = new Canvas(otherBitmap);
expectedDrawable.setBounds(0, 0, otherCanvas.getWidth(), otherCanvas.getHeight());
expectedDrawable.draw(otherCanvas);
return bitmap.sameAs(otherBitmap);
}
return false;
}
Then, create a matcher that checks relative drawables. Here, it verifies only drawable start but you can extend it on our own if you'd like to verify drawable end or top or bottom:
private static Matcher<View> withRelativeDrawables(int expectedDrawableStart) {
return new TypeSafeMatcher<View>() {
@Override
protected boolean matchesSafely(View item) {
if (item instanceof TextView) {
TextView textView = (TextView) item;
//get an array of 4 relative drawables. The first one is drawable start
Drawable[] relativeDrawables = textView.getCompoundDrawablesRelative();
Drawable expectedDrawableStart = ContextCompat.getDrawable(context, expectedDrawableStart);
return sameBitmap(relativeDrawables[0], expectedDrawableStart);
}
return false;
}
@Override
public void describeTo(Description description) {
}
};
}
And then use it as below:
onView(withId(R.id.passwordEditText)).check(matches(withRelativeDrawables(R.drawable.ic_sign_in_password)));
Answered By - Anatolii
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.