Nic*_*ong 17 automated-tests android-testing android-espresso
我想在LinearLayout的textview中显示文本字符串.能浓缩咖啡吗?如果没有,还有其他方法可以做到这一点,还是我可以在espresso测试用例中使用android api?我使用的是API 17 18或更新的espresso 1.1(它应该是最新的.).我对此毫无头绪.谢谢.
haf*_*fax 40
基本思想是使用具有内部ViewAction的方法,该方法在其perform方法中检索文本.匿名类只能访问final字段,因此我们不能让它设置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];
}
Run Code Online (Sandbox Code Playgroud)
注意:应谨慎使用此类视图数据检索器.如果你经常发现自己正在编写这种方法,那么很有可能,你从一开始就做错了什么.也不要访问a之外的View,ViewAssertion或者ViewAction因为只有确保了,所以交互是安全的,因为它是从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");
}
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18083 次 |
| 最近记录: |