Issue
here xml:
<TextView
android:id="@+id/toolbaTitleTextView"
style="@style/textViewOneLine"
android:layout_width="0dp"
android:layout_height="0dp"
android:textAllCaps="true"
android:textColor="@android:color/black"
android:textSize="13sp"
/>
I need to write Espresso test check that TextView has font size (in SP) = 13.
So here test:
@Test
public void toolBarTextSize() {
onView(withId(R.id.toolbaTitleTextView)).check(matches(withFontSize(13)));
}
Here matcher:
public static Matcher<View> withFontSize(final float expectedSize) {
return new BoundedMatcher<View, View>(View.class) {
@Override
public boolean matchesSafely(View target) {
if (!(target instanceof TextView)) {
return false;
}
TextView targetEditText = (TextView) target;
return targetEditText.getTextSize() == expectedSize;
}
@Override
public void describeTo(Description description) {
description.appendText("with fontSize: ");
description.appendValue(expectedSize);
}
};
}
But I get error, because size in pixels.
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with fontSize: <13.0F>' doesn't match the selected view.
Expected: with fontSize: <13.0F>
Got: "AppCompatTextView{id=2131296624, res-name=toolbaTitleTextView, visibility=VISIBLE, width=1080, height=168, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.support.constraint.ConstraintLayout$LayoutParams@13f0b, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=Sign in, input-type=0, ime-target=false, has-links=false}"
But I need in SP. How I can check text size in SP?
Solution
Just convert your size in pixels to the scales pixels. So, your matcher should look like this:
public static Matcher<View> withFontSize(final float expectedSize) {
return new BoundedMatcher<View, View>(View.class) {
@Override
public boolean matchesSafely(View target) {
if (!(target instanceof TextView)) {
return false;
}
TextView targetEditText = (TextView) target;
float pixels = targetEditText.getTextSize();
float actualSize = pixels / target.getResources().getDisplayMetrics().scaledDensity;
return Float.compare(actualSize, expectedSize) == 0;
}
@Override
public void describeTo(Description description) {
description.appendText("with fontSize: ");
description.appendValue(expectedSize);
}
};
}
Answered By - Anatolii
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.