下面列出了怎么用android.support.test.espresso.matcher.ViewMatchers的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void should_be_able_to_show_network_error_when_getting_ip_failed() throws Exception{
//Pre check
onView(withId(R.id.fragment_master_ipValue)).check(
matches(withEffectiveVisibility(ViewMatchers.Visibility.INVISIBLE)));
//Prepare
//Throw an IOException to simulate an network error
IOException ioExceptionMock = mock(IOException.class);
when(ipServiceCallMock.execute()).thenThrow(ioExceptionMock);
//Action
onView(withId(R.id.fragment_master_ipRefresh)).perform(click());
//Check value
onView(withText(R.string.network_error_to_get_ip)).inRoot(
withDecorView(not(is(rule.getActivity().getWindow().getDecorView()))))
.check(matches(isDisplayed()));
}
@Override
public boolean matchesSafely(View view) {
// get visible area for selected view
// it also tell us if at least a small part visible, when not we can abort here
Rect visibleParts = new Rect();
boolean isAtLeastSomethingVisible = view.getGlobalVisibleRect(visibleParts);
if (!isAtLeastSomethingVisible) {
return false;
}
Rect screen = getScreenWithoutStatusBarActionBar(view);
int viewHeight = (view.getHeight() > screen.height()) ? screen.height() : view.getHeight();
int viewWidth = (view.getWidth() > screen.width()) ? screen.width() : view.getWidth();
double maxArea = viewHeight * viewWidth;
double visibleArea = visibleParts.height() * visibleParts.width();
int displayedPercentage = (int) ((visibleArea / maxArea) * 100);
boolean isViewFullVisible = displayedPercentage >= areaPercentage;
return isViewFullVisible && withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE).matches(view);
}
/**
* Test WireMock
*/
@Test
public void testWiremock() {
activity = activityRule.getActivity();
String jsonBody = asset(activity, "atlanta-conditions.json");
stubFor(get(urlMatching("/api/.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(jsonBody)));
String serviceEndpoint = "http://127.0.0.1:" + BuildConfig.PORT;
logger.debug("WireMock Endpoint: " + serviceEndpoint);
activity.setWeatherServiceManager(new WeatherServiceManager(serviceEndpoint));
onView(ViewMatchers.withId(R.id.editText)).perform(replaceText("atlanta"));
onView(withId(R.id.button)).perform(click());
onView(withId(R.id.textView)).check(matches(withText(containsString("GA"))));
}
@Test
public void shouldChangeBackToSubtitleFromErrorMessage() {
//given
onView(allOf(withId(R.id.button), isCompletelyDisplayed())).perform(doubleClick());
onView(withId(R.id.stepperLayout)).perform(clickNext());
onView(withId(R.id.stepperLayout)).perform(clickNext());
onView(allOf(withId(R.id.button), isCompletelyDisplayed())).perform(doubleClick());
//when
onView(withId(R.id.stepperLayout)).perform(clickNext());
//then
checkCurrentStepIs(2);
checkTabSubtitle(0, withEffectiveVisibility(ViewMatchers.Visibility.GONE));
checkTabSubtitle(1, withText(STEP_SUBTITLE));
SpoonScreenshotAction.perform(getScreenshotTag(5, "Change back to subtitle test"));
}
public void testArrayExtrasDisplay() throws Exception {
// Open TestArrayActivity
Espresso.onView(ViewMatchers.withText(R.string.test_array_extras)).perform(ViewActions.click());
// Verify result.
// int arrays
Espresso.onView(ViewMatchers.withText("{1,2,3}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
// long arrays
Espresso.onView(ViewMatchers.withText("{4,5,6}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
// float arrays
Espresso.onView(ViewMatchers.withText("{4.1,5.1,6.1}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
// double arrays
Espresso.onView(ViewMatchers.withText("{7.2,8.2,9.2}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
// boolean arrays
Espresso.onView(ViewMatchers.withText("{true,false,false,true}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
// string arrays
Espresso.onView(ViewMatchers.withText("{One,Two,Three}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
// people
Espresso.onView(ViewMatchers.withText("{{name='p1',age=18},{name='p2',age=19}}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
@Test
public void addMatcher_doesNotNegateMatcher_when_negateNextMatcher_isFalse() {
final Start.Matcher matcher = Cortado.view();
final Cortado cortado = matcher.getCortado();
assertThat(cortado.matchers).hasSize(0);
assertThat(cortado.negateNextMatcher).isFalse();
// no matchers added, negateNextMatcher is false
org.hamcrest.Matcher<View> viewMatcher = ViewMatchers.withText("test");
org.hamcrest.Matcher<View> negatedViewMatcher = Matchers.not(viewMatcher);
cortado.negateNextMatcher = false;
cortado.addMatcher(viewMatcher);
assertThat(cortado.matchers).hasSize(1);
// one matcher added
assertThat(cortado.negateNextMatcher).isFalse();
// negateNextMatcher is still false
final Matcher<? super View> addedMatcher = cortado.matchers.get(0);
Utils.assertThat(addedMatcher).isEqualTo(viewMatcher);
Utils.assertThat(addedMatcher).isNotEqualTo(negatedViewMatcher);
}
private void validateAmountView() {
final Matcher<View> amountDescription = withId(R.id.amount_description);
final Matcher<View> maxCouponAmount = withId(R.id.max_coupon_amount);
final Matcher<View> amountBeforeDiscount =
withId(R.id.amount_before_discount);
final Matcher<View> finalAmount = withId(R.id.final_amount);
final Matcher<View> arrow = withId(R.id.blue_arrow);
onView(amountDescription).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(maxCouponAmount).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
onView(amountBeforeDiscount).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
onView(finalAmount).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(arrow).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
onView(amountDescription).check(matches(withText(
getInstrumentation().getTargetContext().getString(R.string.px_used_up_discount_row))));
onView(amountDescription).check(matches(hasTextColor(R.color.px_form_text)));
}
@Test
public void addMatcher_negatesMatcher_when_negateNextMatcher_isTrue() {
final Start.Matcher matcher = Cortado.view();
final Cortado cortado = matcher.getCortado();
assertThat(cortado.matchers).hasSize(0);
assertThat(cortado.negateNextMatcher).isFalse();
// no matchers added, negateNextMatcher is false
org.hamcrest.Matcher<View> viewMatcher = ViewMatchers.withText("test");
org.hamcrest.Matcher<View> negatedViewMatcher = Matchers.not(viewMatcher);
cortado.negateNextMatcher = true;
cortado.addMatcher(viewMatcher);
assertThat(cortado.matchers).hasSize(1);
// one matcher added
assertThat(cortado.negateNextMatcher).isFalse();
// negateNextMatcher is back to false
final Matcher<? super View> addedMatcher = cortado.matchers.get(0);
Utils.assertThat(addedMatcher).isNotEqualTo(viewMatcher);
Utils.assertThat(addedMatcher).isEqualTo(negatedViewMatcher);
}
@Test
public void testEmptyInputFields() throws Exception {
onView(withId(R.id.loginEdit)).check(matches(allOf(
withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
isFocusable(),
isClickable(),
withText("")
)));
onView(withId(R.id.passwordEdit)).check(matches(allOf(
withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
isFocusable(),
isClickable(),
withInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD),
withText("")
)));
}
@Test
public void clickAppNavigationIconOpenNavigation() {
onView(ViewMatchers.withId(R.id.drawer_layout))
.check(matches(DrawerMatchers.isClosed(Gravity.LEFT)));
onView(withContentDescription(
TestUtils.getToolBarNavigationContentDescription(
mActivityTestRule.getActivity(),
R.id.common_toolbar
))).perform(ViewActions.click());
onView(withId(R.id.drawer_layout))
.check(matches(DrawerMatchers.isOpen(Gravity.LEFT)));
}
@Test
public void ViewMatchers() {
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button));
//onView内部最好不要使用withText()断言处理
Espresso.onView(Matchers.allOf(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button), ViewMatchers.withText("HaHa")));
Espresso.onView(Matchers.allOf(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button), Matchers.not(ViewMatchers.withText("HaHa"))));
}
@Test
public void shouldChangeSubtitleToErrorMessage() {
//given
onView(allOf(withId(R.id.button), isCompletelyDisplayed())).perform(doubleClick());
onView(withId(R.id.stepperLayout)).perform(clickNext());
//when
onView(withId(R.id.stepperLayout)).perform(clickNext());
//then
checkCurrentStepIs(1);
checkTabSubtitle(0, withEffectiveVisibility(ViewMatchers.Visibility.GONE));
checkTabSubtitle(1, withText(ERROR_MESSAGE));
SpoonScreenshotAction.perform(getScreenshotTag(4, "Change subtitle to error message test"));
}
@Test
public void hasContentDescription_addsCorrectMatcher() {
//given
//when
notCompletable.hasContentDescription();
//then
assertExpectedAddedMatcher(ViewMatchers.hasContentDescription());
}
@Test
public void testInvalidData() {
closeSoftKeyboard();
onView(withId(R.id.submit_button)).perform(click());
onView(ViewMatchers.withId(R.id.doc_num))
.check(ViewAssertions.matches(
ViewMatchers.hasErrorText(
activityRule.getActivity().getString(R.string.errInputDocNum))));
}
@Test
public void hasImeAction_withInteger_addsCorrectMatcher() {
//given
//when
notCompletable.hasImeAction(1);
//then
assertExpectedAddedMatcher(ViewMatchers.hasImeAction(1));
}
private void checkOneToOneChatsRecyclerViewContent(final List<String> chatNames) {
RecyclerViewInteraction.<String>onRecyclerView(allOf(withId(R.id.oneToOneChatsRecyclerView), ViewMatchers.isDisplayed()))
.withItems(chatNames)
.check(new RecyclerViewInteraction.ItemViewAssertion<String>() {
@Override
public void check(String chatName, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(chatName))).check(view, e);
}
});
}
@Test
public void isAssignableFrom_addsCorrectMatcher() {
//given
final Class<ImageView> test = ImageView.class;
//when
notCompletable.isAssignableFrom(test);
assertExpectedAddedMatcher(ViewMatchers.isAssignableFrom(test));
}
@Test
public void onTextView_returnsProperViewInteraction() {
//given
final Cortado.OrAnd.ViewInteraction viewInteraction = Cortado.onTextView().withText("test");
final Matcher<View> expectedEspressoMatcher = Matchers.allOf(
ViewMatchers.isAssignableFrom(TextView.class),
viewInteraction.getCortado().matchers.get(0));
//when
final Matcher<View> rawMatcher = viewInteraction.getCortado().get();
//then
Utils.assertThat(rawMatcher).isEqualTo(expectedEspressoMatcher);
}
private void checkGroupChatsRecyclerViewContent(final List<String> chatNames) {
RecyclerViewInteraction.<String>onRecyclerView(allOf(withId(R.id.groupChatsRecyclerView), ViewMatchers.isDisplayed()))
.withItems(chatNames)
.check(new RecyclerViewInteraction.ItemViewAssertion<String>() {
@Override
public void check(String chatName, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(chatName))).check(view, e);
}
});
}
@Test
public void withInputType_addsCorrectMatcher() {
//given
//when
notCompletable.withInputType(1);
//then
assertExpectedAddedMatcher(ViewMatchers.withInputType(1));
}
@Test
public void testHideProgressBar() {
apiConfig.setCorrectAnswer();
enterOwner();
onView(withId(R.id.toolbar_progress_bar)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.INVISIBLE)));
}
@Test
public void withParent_withMatcher_addsCorrectMatcher() {
//given
org.hamcrest.Matcher<View> testMatcher = SimpleMatcher.instance();
//when
notCompletable.withParent(testMatcher);
//then
assertExpectedAddedMatcher(ViewMatchers.withParent(testMatcher));
}
@NonNull
final synchronized org.hamcrest.Matcher<View> get() {
if (cached == null) {
cached = linker.link(matchers);
if (assignableFromClass != null) {
List<org.hamcrest.Matcher<? super View>> assignedMatchers = new ArrayList<>(2);
assignedMatchers.add(ViewMatchers.isAssignableFrom(assignableFromClass));
assignedMatchers.add(cached);
cached = Linker.AND.link(assignedMatchers);
}
}
//noinspection unchecked
return (org.hamcrest.Matcher<View>) cached;
}
@Test
public void withContentDescription_withString_addsCorrectMatcher() {
//given
//when
notCompletable.withContentDescription("test");
//then
assertExpectedAddedMatcher(ViewMatchers.withContentDescription("test"));
}
@Test
public void withChild_withMatcher_addsCorrectMatcher() {
//given
org.hamcrest.Matcher<View> testMatcher = SimpleMatcher.instance();
//when
notCompletable.withChild(testMatcher);
//then
assertExpectedAddedMatcher(ViewMatchers.withChild(testMatcher));
}
@Test
public void withSpinnerText_withString_addsCorrectMatcher() {
//given
//when
notCompletable.withSpinnerText("test");
//then
assertExpectedAddedMatcher(ViewMatchers.withSpinnerText("test"));
}
@Test
public void withTagKey_addsCorrectMatcher() {
//given
//when
notCompletable.withTagKey(1);
//then
assertExpectedAddedMatcher(ViewMatchers.withTagKey(1));
}
@Test
public void isEnabled_addsCorrectMatcher() {
//given
//when
notCompletable.isEnabled();
//then
assertExpectedAddedMatcher(ViewMatchers.isEnabled());
}
public void testStartActivityTestStringExtra2UsingDefaultValue() throws Exception {
final String extra2 = "Nguyen";
Espresso.onView(ViewMatchers.withHint(R.string.string_extra_2)).perform(ViewActions.typeText(extra2));
Espresso.closeSoftKeyboard();
Espresso.onView(ViewMatchers.withText(R.string.submit)).perform(ExtViewActions.waitForSoftKeyboard(), ViewActions.click());
Espresso.onView(ViewMatchers.withText("Default")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withText(extra2)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
@Test
public void withParent_withCortadoMatcher_addsCorrectMatcher() {
//given
Matcher testMatcher = Cortado.view().withText("Test");
//when
notCompletable.withParent(testMatcher);
//then
assertExpectedAddedMatcher(ViewMatchers.withParent(testMatcher));
}