lig*_*igi 41 testing android android-espresso
我试图通过以下方式点击一些Espresso测试中的主页图标:
onView(withId(android.R.id.home)).perform(click());
Run Code Online (Sandbox Code Playgroud)
这适用于Android> 3.0 - 但旧版本失败,appcompat因为这个元素似乎没有使用此ID.做我想做的事情的好方法是什么?
sun*_*er3 74
要不依赖于应用程序区域设置,可以使用Matt Logan中的代码,将Rstring.abc_action_bar_up_description替换为"向上导航":
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());
Run Code Online (Sandbox Code Playgroud)
这对我帮助很大,因为我有一个超过5种语言的应用程序,我必须这样做.
Mat*_*gan 27
使用withContentDescription() Matcher:
onView(withContentDescription("Navigate up")).perform(click());
Run Code Online (Sandbox Code Playgroud)
Igo*_*pov 18
我无法从一个Activity导航到另一个Activity,但后来我发现了顶级操作:
Espresso.pressBack();
Run Code Online (Sandbox Code Playgroud)
mre*_*elt 14
我找到了解决这个问题的真正方法.通过使用hierarchyviewer我发现工具栏看起来像这样:

这意味着我们可以匹配汉堡包图标(不是后退按钮),如下所示:
onView(withContentDescription("Open navigation")).perform(click());
Run Code Online (Sandbox Code Playgroud)
但对我来说更好的解决方案是发现汉堡图标是唯一的ImageButton和v7工具栏的直接子视图.所以我写了一个辅助方法来匹配它:
public static Matcher<View> androidHomeMatcher() {
return allOf(
withParent(withClassName(is(Toolbar.class.getName()))),
withClassName(anyOf(
is(ImageButton.class.getName()),
is(AppCompatImageButton.class.getName())
)));
}
@Test
public void clickHamburgerIcon() throws Exception {
onView(androidHomeMatcher()).perform(click());
// ...
}
Run Code Online (Sandbox Code Playgroud)
此解决方案更好,因为无论您在测试中使用哪种语言环境,它都应与视图匹配.:-)
编辑:请注意,工具栏可能是android.support.v7.widget.Toolbar或android.widget.Toolbar - 取决于您的用例!
编辑:支持lib版本24.2.0使用AppCompatImageButton而不是ImageButton,所以我也添加了它.
编辑:您必须导入正确的方法才能使其工作.以下是使用的进口:
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
Run Code Online (Sandbox Code Playgroud)
小智 5
Espresso.pressBack();
Run Code Online (Sandbox Code Playgroud)
或者
onView(withContentDescription("Navigate up")).perform(click());
Run Code Online (Sandbox Code Playgroud)
我在模拟器中遇到"导航"问题,这对我有用:
onView(isRoot()).perform(ViewActions.pressMenuKey());
Run Code Online (Sandbox Code Playgroud)
小智 5
public static Matcher<View> navigationIconMatcher() {
return allOf(
isAssignableFrom(ImageButton.class),
withParent(isAssignableFrom(Toolbar.class)));
}
@Test
public void clickHamburgerIcon() throws Exception {
onView(navigationIconMatcher()).perform(click());
// ...
}
Run Code Online (Sandbox Code Playgroud)
这总是有效!
| 归档时间: |
|
| 查看次数: |
18780 次 |
| 最近记录: |