下面列出了怎么用android.support.test.espresso.NoMatchingViewException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void clickOnElection() throws Exception {
final Election e = electionActivity.getAdapter().getItem(1);
onData(instanceOf(Election.class)) // We are using the position so don't need to specify a data matcher
.inAdapterView(withId(R.id.election_list)) // Specify the explicit id of the ListView
.atPosition(1) // Explicitly specify the adapter item to use
.perform(click());
// intended(hasComponent(MainActivity.class.getName()));
onView(withId(R.id.app_bar)).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
assertEquals(((Toolbar) view).getTitle(), e.getKind());
assertEquals(((Toolbar) view).getSubtitle(), e.getPlace());
}
});
}
@Test
public void searchCityAndClick() throws Exception {
List<Election> unfilteredList = electionActivity.getAdapter().getList();
onView(withId(R.id.search)).perform(click());
final Election toClick = unfilteredList.get(0);
onView(withId(android.support.design.R.id.search_src_text)).perform(typeText(toClick.getPlace()));
onView (withId (R.id.election_list)).check (ViewAssertions.matches (new Matchers().withListSize (1)));
onData(instanceOf(Election.class))
.inAdapterView(withId(R.id.election_list))
.atPosition(0)
.perform(click());
// intended(hasComponent(MainActivity.class.getName()));
onView(withId(R.id.app_bar)).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
assertEquals(((Toolbar) view).getTitle(), toClick.getKind());
assertEquals(((Toolbar) view).getSubtitle(), toClick.getPlace());
}
});
}
public static ViewAssertion flexGridHasCode(final List<CodeLine> expectedCodeLines)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
FlexGrid flexGrid = (FlexGrid) view;
List<CodeLine> actualCodeLines = (List<CodeLine>) flexGrid.getItemsSource();
for (int i = 0; i < expectedCodeLines.size(); i++)
{
CodeLine expected = expectedCodeLines.get(i);
CodeLine actual = actualCodeLines.get(i);
assertEquals(expected.getCodeText(), actual.getCodeText());
}
}
};
}
/**
* Check that this item exist.
*
* Is true when adapter has matching item ignores the display state.
*
* @since Espresso Macchiato 0.6
*/
public void assertExist() {
findRecyclerView().check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
if (noViewFoundException != null) {
throw noViewFoundException;
}
RecyclerView recyclerView = (RecyclerView) view;
if (index >= recyclerView.getAdapter().getItemCount()) {
throw new AssertionFailedError("Requested item should exist.");
}
}
});
}
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
if (noViewFoundException != null) {
throw noViewFoundException;
}
RecyclerView recyclerView = (RecyclerView) view;
if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
int spanCount = gridLayoutManager.getSpanCount();
if (spanCount != expectedColumnCount) {
String errorMessage = "expected column count " + expectedColumnCount
+ " but was " + spanCount;
throw new AssertionError(errorMessage);
}
} else {
throw new IllegalStateException("no grid layout manager");
}
}
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
if (noViewFoundException != null) {
throw noViewFoundException;
}
RecyclerView recyclerView = (RecyclerView) view;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
boolean indexInRange = firstVisibleItem <= index && index <= lastVisibleItem;
if ((shouldBeVisible && !indexInRange) || (!shouldBeVisible && indexInRange)) {
String errorMessage = "expected item " + index + " to " +
(shouldBeVisible ? "" : "not") + " be visible, but was" +
(indexInRange ? "" : " not") + " visible";
throw new AssertionError(errorMessage);
}
}
}
@Test
public void testAutoFocus() {
onView(withId(R.id.camera))
.check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
CameraView cameraView = (CameraView) view;
// This can fail on devices without auto-focus support
assertThat(cameraView.getAutoFocus(), is(true));
cameraView.setAutoFocus(false);
assertThat(cameraView.getAutoFocus(), is(false));
cameraView.setAutoFocus(true);
assertThat(cameraView.getAutoFocus(), is(true));
}
});
}
private static ViewAssertion showingPreview() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
CameraView cameraView = (CameraView) view;
TextureView textureView = cameraView.findViewById(R.id.texture_view);
Bitmap bitmap = textureView.getBitmap();
int topLeft = bitmap.getPixel(0, 0);
int center = bitmap.getPixel(bitmap.getWidth() / 2, bitmap.getHeight() / 2);
int bottomRight = bitmap.getPixel(
bitmap.getWidth() - 1, bitmap.getHeight() - 1);
assertFalse("Preview possibly blank: " + Integer.toHexString(topLeft),
topLeft == center && center == bottomRight);
}
};
}
public static ViewAssertion checkMessagesOnlyFromToday() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
RecyclerMessageAdapter recyclerMessageAdapter = (RecyclerMessageAdapter) rv.getAdapter();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("OfDate-" + (new Date()).toString() + " { ");
for (int index = 0; index < recyclerMessageAdapter.getItemCount(); index++) {
if (recyclerMessageAdapter.getItem(index) instanceof Message) {
Message message = (Message) recyclerMessageAdapter.getItem(index);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.US);
stringBuilder.append(message.getID() + "-" + sdf.format(message.getTimestamp()) + " , ");
assertTrue("This message is not of today ID=" + message.getID() + ":" + message.getIdForHolder() + "\ncontent=" + message.getContent(), DateUtils.isToday(message.getTimestamp().getTime()));
}
}
stringBuilder.append(" }");
printLogInPartsIfExceeded(stringBuilder, "checkMessagesOnlyFromToday");
}
};
}
public static ViewAssertion hasViewWithTextAtPosition(final int index, final CharSequence text) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
ArrayList<View> outviews = new ArrayList<>();
rv.findViewHolderForAdapterPosition(index).itemView.findViewsWithText(outviews, text,
FIND_VIEWS_WITH_TEXT);
Truth.assert_().withFailureMessage("There's no view at index " + index + " of recyclerview that has text : " + text)
.that(outviews).isNotEmpty();
}
};
}
public static ViewAssertion doesntHaveViewWithText(final String text) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
ArrayList<View> outviews = new ArrayList<>();
for (int index = 0; index < rv.getAdapter().getItemCount(); index++) {
rv.findViewHolderForAdapterPosition(index).itemView.findViewsWithText(outviews, text,
FIND_VIEWS_WITH_TEXT);
if (outviews.size() > 0) break;
}
Truth.assertThat(outviews).isEmpty();
}
};
}
@Override
public void handle(Throwable error, Matcher<View> viewMatcher) {
try {
delegate.handle(error, viewMatcher);
} catch (NoMatchingViewException e) {
// For example done device dump, take screenshot, etc.
throw e;
}
}
@Test
public void atElectionActivity() throws Exception {
onView(withId(R.id.app_bar)).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
assertEquals(((Toolbar) view).getTitle(), "Choose election");
}
});
}
@Override
public void check (View view, NoMatchingViewException noViewFoundException) {
if (noViewFoundException != null) {
throw noViewFoundException;
}
RecyclerView recyclerView = (RecyclerView) view;
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (mode == MODE_EQUALS) {
assertThat(expectedChildCount, is(adapter.getItemCount()));
} else if (mode == MODE_LESS_THAN) {
assertTrue(expectedChildCount > adapter.getItemCount());
}
}
public static ViewAssertion flexGridReadOnly(final boolean expected)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
FlexGrid flexGrid = (FlexGrid) view;
assertEquals(expected, flexGrid.isReadOnly());
}
};
}
public static ViewAssertion mockDrawable(final String expectedTag)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
String tag = (String) ((MockDrawable) ((ImageView) view).getDrawable()).getTag();
assertEquals(expectedTag, tag);
}
};
}
public static ViewAssertion withDrawable(@DrawableRes final int expectedResourceId)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
@DrawableRes int tag = (int) ((MockDrawable) ((ImageView) view).getDrawable()).getTag();
assertEquals(expectedResourceId, tag);
}
};
}
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
T key = Flow.getKey(view);
if(key == null || !key.equals(this.key)) {
throw new AssertionError("Key [" + key + "] does not equal [" + this.key + "]");
}
}
private void checkRecyclerViewContent(final List<String> users) {
RecyclerViewInteraction.<String>onRecyclerView(allOf(withId(R.id.chatMembersRecyclerView), ViewMatchers.isDisplayed()))
.withItems(users)
.check(new RecyclerViewInteraction.ItemViewAssertion<String>() {
@Override
public void check(String user, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(XMPPUtils.fromJIDToUserName(user)))).check(view, e);
}
});
}
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);
}
});
}
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);
}
});
}
private void checkBlogPostsRecyclerViewContent(final List<String> blogPosts) {
RecyclerViewInteraction.<String>onRecyclerView(allOf(withId(R.id.blogsRecyclerView), ViewMatchers.isDisplayed()))
.withItems(blogPosts)
.check(new RecyclerViewInteraction.ItemViewAssertion<String>() {
@Override
public void check(String blogPost, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(blogPost))).check(view, e);
}
});
}
private void checkBlogPostsRecyclerViewContent(final List<String> comments) {
RecyclerViewInteraction.<String>onRecyclerView(allOf(withId(R.id.recyclerviewComments), isDisplayed()))
.withItems(comments)
.check(new RecyclerViewInteraction.ItemViewAssertion<String>() {
@Override
public void check(String comment, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(comment))).check(view, e);
}
});
}
private void checkRecyclerViewContent(final List<String> users) {
RecyclerViewInteraction.<String>onRecyclerView(allOf(withId(R.id.membersRecyclerView), ViewMatchers.isDisplayed()))
.withItems(users)
.check(new RecyclerViewInteraction.ItemViewAssertion<String>() {
@Override
public void check(String user, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(XMPPUtils.fromJIDToUserName(user)))).check(view, e);
}
});
}
@Override
public final void check(View view, NoMatchingViewException e) {
RecyclerView recyclerView = (RecyclerView) view;
RecyclerView.ViewHolder viewHolderForPosition = recyclerView.findViewHolderForLayoutPosition(position);
if (viewHolderForPosition == null) {
throw (new PerformException.Builder())
.withActionDescription(toString())
.withViewDescription(HumanReadables.describe(view))
.withCause(new IllegalStateException("No view holder at position: " + position))
.build();
} else {
View viewAtPosition = viewHolderForPosition.itemView;
itemViewAssertion.check(item, viewAtPosition, e);
}
}
@Override public final void check(View view, NoMatchingViewException e) {
RecyclerView recyclerView = (RecyclerView) view;
RecyclerView.ViewHolder viewHolderForPosition =
recyclerView.findViewHolderForLayoutPosition(position);
if (viewHolderForPosition == null) {
throw (new PerformException.Builder()).withActionDescription(toString())
.withViewDescription(HumanReadables.describe(view))
.withCause(new IllegalStateException("No view holder at position: " + position))
.build();
} else {
View viewAtPosition = viewHolderForPosition.itemView;
itemViewAssertion.check(item, viewAtPosition, e);
}
}
@Test public void showsSuperHeroesNameIfThereAreSuperHeroes() {
List<SuperHero> superHeroes = givenThereAreSomeSuperHeroes(ANY_NUMBER_OF_SUPER_HEROES);
startActivity();
RecyclerViewInteraction.<SuperHero>onRecyclerView(withId(R.id.recycler_view))
.withItems(superHeroes)
.check(new RecyclerViewInteraction.ItemViewAssertion<SuperHero>() {
@Override public void check(SuperHero superHero, View view, NoMatchingViewException e) {
matches(hasDescendant(withText(superHero.getName()))).check(view, e);
}
});
}
@Test public void showsAvengersBadgeIfASuperHeroIsPartOfTheAvengersTeam() {
List<SuperHero> superHeroes = givenThereAreSomeAvengers(ANY_NUMBER_OF_SUPER_HEROES);
startActivity();
RecyclerViewInteraction.<SuperHero>onRecyclerView(withId(R.id.recycler_view))
.withItems(superHeroes)
.check(new RecyclerViewInteraction.ItemViewAssertion<SuperHero>() {
@Override public void check(SuperHero superHero, View view, NoMatchingViewException e) {
matches(hasDescendant(allOf(withId(R.id.iv_avengers_badge),
withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))).check(view, e);
}
});
}
@Test public void doesNotShowAvengersBadgeIfASuperHeroIsNotPartOfTheAvengersTeam() {
List<SuperHero> superHeroes = givenThereAreSomeSuperHeroes(ANY_NUMBER_OF_SUPER_HEROES, false);
startActivity();
RecyclerViewInteraction.<SuperHero>onRecyclerView(withId(R.id.recycler_view))
.withItems(superHeroes)
.check(new RecyclerViewInteraction.ItemViewAssertion<SuperHero>() {
@Override public void check(SuperHero superHero, View view, NoMatchingViewException e) {
matches(hasDescendant(allOf(withId(R.id.iv_avengers_badge),
withEffectiveVisibility(ViewMatchers.Visibility.GONE)))).check(view, e);
}
});
}
public static ViewAssertion haveItemCount(final int count) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
StringDescription description = new StringDescription();
description.appendText("'");
if (noViewFoundException != null) {
description.appendText(String.format(
"' check could not be performed because view '%s' was not found.\n",
noViewFoundException.getViewMatcherDescription()));
Log.e(TAG, description.toString());
throw noViewFoundException;
} else {
int actualCount = -1;
if (view instanceof RecyclerView) {
actualCount = getItemCount((RecyclerView) view);
}
if (actualCount == -1) {
throw new AssertionError("Cannot get view item count.");
} else if (actualCount != count) {
throw new AssertionError("View has " + actualCount +
"items while expected " + count);
}
}
}
};
}