Espresso在布局中获得动态创建的子项

时间:2015-07-31 21:12:27

标签: android unit-testing android-espresso

Button.java

public class Button extends FrameLayout {
    public Button(Context context, AttributeSet attrs) {
        super(context, attrs);
        TextView textView = new TextView(context);
        textView.setText("Test");
    }
}

layout.xml

<LinearLayout>
    <com.Button id="button_1" />
    <com.Button id="button_2" />
</LinearLayout>

使用Espresso,如何访问TextView中创建的Button并验证其文字?

onView(withId(R.id.button_1)<get_child>).check(matches(withText("Test")));

1 个答案:

答案 0 :(得分:1)

onView(withId(R.id.button_1)).check(matches(withChildText("Test")));

static Matcher<View> withChildText(final String string) {
    return new BoundedMatcher<View, FrameLayout>(FrameLayout.class) {
        @Override
        public boolean matchesSafely(FrameLayout view) {
            View child = view.getChildAt(0);
            if (child != null && child instanceof TextView) {
                return ((TextView) child).getText().toString().equals(string);
            }
            return false;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("with child text: ");
        }
    };
}