3

I am having problems to test display word in ITALIC style. Can someone provide me any example code to display word style? I am using Espresso and JUnit 4 in android studio. I really appreciated your cooperation. Thank you

intan
  • 31
  • 3

2 Answers2

3

Please try out the following solution. It might work for you. The core idea is considering using custom ViewMatcher for your case.

public static Matcher<View> withItalicStyle(final int resourceId) {
    return new TypeSafeMatcher<View>() {
        @Override
        public void describeTo(Description description) {
            description.appendText("has Italic Text with resource" );
        }

        @Override
        public boolean matchesSafely(View view) {
            TextView textView = (TextView) view.findViewById(resourceId);
            return (textView.getTypeface().getStyle() == Typeface.ITALIC);
        }
    };
}

And in you testcase, you can

    onView(CustomMatchers.withItalicStyle(R.id.yourResourceId)).check(isDisplayed());

For tutorial, please check goole samples in https://github.com/googlesamples/android-testing/blob/master/ui/espresso/IdlingResourceSample/app/src/main/java/com/example/android/testing/espresso/IdlingResourceSample/MainActivity.java

Wae
  • 106
  • 7
  • 3
    You can avoid casting with the [BoundedMatcher](https://developer.android.com/reference/android/support/test/espresso/matcher/BoundedMatcher.html) – Be_Negative Aug 27 '17 at 01:47
0

Building on Wae's solution but using BoundedMatcher (and Kotlin):

fun hasTextStyle(textStyle: Int): Matcher<View> {
    return object : BoundedMatcher<View,TextView>(TextView::class.java) {
        override fun describeTo(description: Description) {
            description.appendText("has specified text style")
        }

        override fun matchesSafely(item: TextView): Boolean {
            return item.typeface.style == textStyle
        }
    }
}

Use it like onView(withId(R.id.example)).check(matches(hasTextStyle(Typeface.ITALIC)))

Adam Burley
  • 5,551
  • 4
  • 51
  • 72