自动化测试-如何使用espresso从textview中获取文本



我想要在LinearLayout中的文本视图中显示文本字符串。浓缩咖啡能做到吗?如果没有,有其他方法可以做到这一点吗?或者我可以在espresso测试用例中使用android api吗?我正在使用API 17 18或更新版本,浓缩咖啡1.1(这应该是最新的一款。)。我对此一无所知。谢谢

基本思想是使用一个带有内部ViewAction的方法,该方法在其执行方法中检索文本。匿名类只能访问最终字段,所以我们不能只让它设置getText()的局部变量,而是使用String数组来从ViewAction中获取字符串。

    String getText(final Matcher<View> matcher) {
        final String[] stringHolder = { null };
        onView(matcher).perform(new ViewAction() {
            @Override
            public Matcher<View> getConstraints() {
                return isAssignableFrom(TextView.class);
            }
    
            @Override
            public String getDescription() {
                return "getting text from a TextView";
            }
    
            @Override
            public void perform(UiController uiController, View view) {
                TextView tv = (TextView)view; //Save, because of check in getConstraints()
                stringHolder[0] = tv.getText().toString();
            }
        });
        return stringHolder[0];
    }

注意:应小心使用这种视图数据检索器。如果你经常发现自己在写这种方法,很有可能,你从一开始就做错了什么。此外,永远不要访问ViewAssertionViewAction之外的视图,因为只有在那里才能确保交互是安全的,因为它是从UI线程运行的,并且在执行之前会检查它,没有其他交互会干预。

如果您想用另一个文本检查文本值,可以创建Matcher。你可以看到我的代码来创建你自己的方法:

 public static Matcher<View> checkConversion(final float value){
    return new TypeSafeMatcher<View>() {
        @Override
        protected boolean matchesSafely(View item) {
            if(!(item instanceof TextView)) return false;
            float convertedValue = Float.valueOf(((TextView) item).getText().toString());
            float delta = Math.abs(convertedValue - value);
            return delta < 0.005f;
        }
        @Override
        public void describeTo(Description description) {
            description.appendText("Value expected is wrong");
        }
    };
}

最新更新