我在YT Advanced Android Espresso找到了很棒的乐器测试教程。我从那里拿了代码,对我的需求进行了小调整。
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withChild;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;
...
@Test
public void checkToolbarTitle() {
String toolbarTitile = getInstrumentation().getTargetContext().getString(R.string.my_bus_stops);
onView(allOf(isAssignableFrom(TextView.class), withParent(isAssignableFrom(Toolbar.class)))).check(matches(withText(toolbarTitile)));
}
不幸的是,这对我不起作用。测试失败:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (is assignable from class: class android.widget.TextView and has parent matching: is assignable from class: class android.widget.Toolbar)
它出了什么问题?我怎样才能以其他方式测试呢?
答案 0 :(得分:21)
这对我有用:
onView(allOf(instanceOf(TextView.class), withParent(withId(R.id.toolbar))))
.check(matches(withText("toolbarTitile")));
答案 1 :(得分:8)
<强>解强>
方法很好。正如Chiu-Ki Chan在她的教程中写道,你可以指出一个特定的观点&#34;。 但您必须确保导入了正确的工具栏:
import android.support.v7.widget.Toolbar;
而不是:
import android.widget.Toolbar;
答案 2 :(得分:5)
如果您使用的是ActionBar,而不是工具栏,请使用:
onView(allOf(instanceOf(TextView.class),
withParent(withResourceName("action_bar"))))
.check(matches(withText("My ActionBar title")));
答案 3 :(得分:4)
这是一种替代方法(也是惯用的方法):
onView(withId(R.id.toolbar)).check(matches(hasDescendant(withText(toolbarTitle))))
答案 4 :(得分:3)
我不记得我是自己写的,还是我在某个地方找到了它,但这就是我检查工具栏标题的方式:
public static Matcher<View> withToolbarTitle(CharSequence title) {
return withToolbarTitle(is(title));
}
public static Matcher<View> withToolbarTitle(final Matcher<CharSequence> textMatcher) {
return new BoundedMatcher<View, Toolbar>(Toolbar.class) {
@Override
public boolean matchesSafely(Toolbar toolbar) {
return textMatcher.matches(toolbar.getTitle());
}
@Override
public void describeTo(Description description) {
description.appendText("with toolbar title: ");
textMatcher.describeTo(description);
}
};
}
这适用于所有情况。断言示例:onView(withId(R.id.toolbar)).check(matches(withToolbarTitle("title")));