下面列出了怎么用android.support.test.espresso.PerformException的API类实例代码及写法,或者点击链接到github查看源代码。
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
(new ScrollToPositionViewAction(this.position)).perform(uiController, view);
uiController.loopMainThreadUntilIdle();
View targetView = recyclerView.getChildAt(this.position).findViewById(this.viewId);
if (targetView == null) {
throw (new PerformException.Builder()).withActionDescription(this.toString())
.withViewDescription(
HumanReadables.describe(view))
.withCause(new IllegalStateException(
"No view with id "
+ this.viewId
+ " found at position: "
+ this.position))
.build();
} else {
this.viewAction.perform(uiController, targetView);
}
}
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
(new ScrollToPositionViewAction(this.position)).perform(uiController, view);
uiController.loopMainThreadUntilIdle();
View targetView = recyclerView.getChildAt(this.position).findViewById(this.viewId);
if (targetView == null) {
throw (new PerformException.Builder()).withActionDescription(this.toString())
.withViewDescription(
HumanReadables.describe(view))
.withCause(new IllegalStateException(
"No view with id "
+ this.viewId
+ " found at position: "
+ this.position))
.build();
} else {
this.viewAction.perform(uiController, targetView);
}
}
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
(new ScrollToPositionViewAction(this.position)).perform(uiController, view);
uiController.loopMainThreadUntilIdle();
View targetView = recyclerView.getChildAt(this.position).findViewById(this.viewId);
if (targetView == null) {
throw (new PerformException.Builder()).withActionDescription(this.toString())
.withViewDescription(
HumanReadables.describe(view))
.withCause(new IllegalStateException(
"No view with id "
+ this.viewId
+ " found at position: "
+ this.position))
.build();
} else {
this.viewAction.perform(uiController, targetView);
}
}
@Override
public final void perform(UiController uiController, View view) {
uiController.loopMainThreadUntilIdle();
long finishTime = System.currentTimeMillis() + duration;
while (System.currentTimeMillis() < finishTime) {
if (isConditionMet(view)) {
return;
}
uiController.loopMainThreadForAtLeast(50L);
}
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new TimeoutException())
.build();
}
@Override
public void perform(UiController uiController, View view) {
try {
RecyclerView recyclerView = (RecyclerView) view;
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter instanceof TasksFragment.TasksAdapter) {
for (int i = 0; i < adapter.getItemCount(); i++) {
View taskItemView = recyclerView.getLayoutManager().findViewByPosition(i);
if (taskItemView != null) {
TextView textView = taskItemView.findViewById(R.id.todo_title);
if (textView != null && textView.getText() != null) {
if (textView.getText().toString().equals(toDoTitle)) {
CheckBox completeCheckBox = taskItemView.findViewById(R.id.todo_complete);
completeCheckBox.performClick();
}
} else {
throw new RuntimeException(
"Unable to find TO-DO item with title \"" + toDoTitle + "\"");
}
}
}
}
uiController.loopMainThreadForAtLeast(ViewConfiguration.getTapTimeout());
} catch (RuntimeException e) {
throw new PerformException.Builder().withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view)).withCause(e).build();
}
}
@Override
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
int itemCount = recyclerView.getAdapter().getItemCount();
try {
recyclerView.scrollToPosition(itemCount - 1);
uiController.loopMainThreadUntilIdle();
} catch (RuntimeException e) {
throw new PerformException.Builder().withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view)).withCause(e).build();
}
}
@Test
public void testFaultyClickArgumentsView() {
expectedException.expect(PerformException.class);
expectedException.expectCause(allOf(
isA(SporkRuntimeException.class),
hasMessage(containsString("onClick() failed because the method arguments are invalid"))
));
TestFaultyClickArgumentsView view = activityRule.getActivity().getTestFaultyClickArgumentsView();
assertNotNull(view);
onView(withId(view.getId())).perform(click());
}
@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);
}
}
@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);
}
}
private void checkIsNotEmpty(View view, StringDescription description) {
if (sortedList.isEmpty()) {
description.appendText("The list must be not empty");
throw (new PerformException.Builder())
.withActionDescription(description.toString())
.withViewDescription(HumanReadables.describe(view))
.withCause(new IllegalStateException("The list is empty"))
.build();
}
}
@Test(expected = PerformException.class)
public void Verify_Throw_Next_Step_When_Steps_Left() {
onView(withId(R.id.bt_next)).perform(click());
onView(withId(R.id.bt_next)).perform(click());
onView(withId(R.id.bt_next)).perform(click());
onView(withId(R.id.bt_next)).perform(click());
onView(withId(R.id.bt_next)).perform(click());
}
public static ViewAction waitId(final int viewId, final long millis) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isRoot();
}
@Override
public String getDescription() {
return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
}
@Override
public void perform(final UiController uiController, final View view) {
uiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + millis;
final Matcher<View> viewMatcher = withId(viewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
// found view with required ID
if (viewMatcher.matches(child)) {
return;
}
}
uiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
// timeout happens
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new TimeoutException())
.build();
}
};
}
/**
* Tests if the app crashes when the crash button is pressed
*/
@Test(expected = PerformException.class)
public void testVerifyCrash(){
checkIfIdIsDisplayedWithText(R.id.bug_fragment_message, R.string.crash_headline);
try {
clickId(R.id.crash_button);
fail("App did not crash");
} catch (PerformException e ){}
}
@Override
public void perform(UiController uiController, View view) {
float[] coordinates = coordinatesProvider.calculateCoordinates(view);
float[] precision = precisionDescriber.describePrecision();
Tapper.Status status = Tapper.Status.FAILURE;
int loopCount = 0;
// Native event injection is quite a tricky process. A tap is actually 2
// seperate motion events which need to get injected into the system. Injection
// makes an RPC call from our app under test to the Android system server, the
// system server decides which window layer to deliver the event to, the system
// server makes an RPC to that window layer, that window layer delivers the event
// to the correct UI element, activity, or window object. Now we need to repeat
// that 2x. for a simple down and up. Oh and the down event triggers timers to
// detect whether or not the event is a long vs. short press. The timers are
// removed the moment the up event is received (NOTE: the possibility of eventTime
// being in the future is totally ignored by most motion event processors).
//
// Phew.
//
// The net result of this is sometimes we'll want to do a regular tap, and for
// whatever reason the up event (last half) of the tap is delivered after long
// press timeout (depending on system load) and the long press behaviour is
// displayed (EG: show a context menu). There is no way to avoid or handle this more
// gracefully. Also the longpress behavour is app/widget specific. So if you have
// a seperate long press behaviour from your short press, you can pass in a
// 'RollBack' ViewAction which when executed will undo the effects of long press.
while (status != Tapper.Status.SUCCESS && loopCount < 3) {
try {
status = tapper.sendTap(uiController, coordinates, precision);
} catch (RuntimeException re) {
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(re)
.build();
}
// ensures that all work enqueued to process the tap has been run.
uiController.loopMainThreadForAtLeast(ViewConfiguration.getPressedStateDuration());
if (status == Tapper.Status.WARNING) {
if (rollbackAction.isPresent()) {
rollbackAction.get().perform(uiController, view);
} else {
break;
}
}
loopCount++;
}
if (status == Tapper.Status.FAILURE) {
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new RuntimeException(String.format("Couldn't "
+ "click at: %s,%s precision: %s, %s . Tapper: %s coordinate provider: %s precision " +
"describer: %s. Tried %s times. With Rollback? %s", coordinates[0], coordinates[1],
precision[0], precision[1], tapper, coordinatesProvider, precisionDescriber, loopCount,
rollbackAction.isPresent())))
.build();
}
if (tapper == Tap.SINGLE && view instanceof WebView) {
// WebViews will not process click events until double tap
// timeout. Not the best place for this - but good for now.
uiController.loopMainThreadForAtLeast(ViewConfiguration.getDoubleTapTimeout());
}
}
public static ViewAction nestedScrollTo() {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return allOf(isDescendantOfA(isAssignableFrom(NestedScrollView.class)), withEffectiveVisibility(
ViewMatchers.Visibility.VISIBLE));
}
@Override
public String getDescription() {
return "Scrolling to view inside NestedScrollView";
}
@Override
public void perform(final UiController uiController, final View view) {
try {
final NestedScrollView nestedScrollView = (NestedScrollView)
findFirstParentLayoutOfClass(view, NestedScrollView.class);
if (nestedScrollView != null) {
final CoordinatorLayout coordinatorLayout =
(CoordinatorLayout) findFirstParentLayoutOfClass(view, CoordinatorLayout.class);
if (coordinatorLayout != null) {
final CollapsingToolbarLayout collapsingToolbarLayout =
findCollapsingToolbarLayoutChildIn(coordinatorLayout);
if (collapsingToolbarLayout != null) {
final int toolbarHeight = collapsingToolbarLayout.getHeight();
nestedScrollView.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
nestedScrollView.dispatchNestedPreScroll(0, toolbarHeight, null, null);
}
}
nestedScrollView.scrollTo(0, view.getTop());
} else {
throw new Exception("Unable to find NestedScrollView parent.");
}
} catch (final Exception e) {
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(e)
.build();
}
uiController.loopMainThreadUntilIdle();
}
};
}
@Override
public void perform(UiController uiController, View view) {
float[] startCoordinates = startCoordinatesProvider.calculateCoordinates(view);
float[] endCoordinates = endCoordinatesProvider.calculateCoordinates(view);
float[] precision = precisionDescriber.describePrecision();
Swiper.Status status = Swiper.Status.FAILURE;
for (int tries = 0; tries < MAX_TRIES && status != Swiper.Status.SUCCESS; tries++) {
try {
status = swiper.sendSwipe(uiController, startCoordinates, endCoordinates, precision);
} catch (RuntimeException re) {
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(re)
.build();
}
int duration = ViewConfiguration.getPressedStateDuration();
// ensures that all work enqueued to process the swipe has been run.
if (duration > 0) {
uiController.loopMainThreadForAtLeast(duration);
}
}
if (status == Swiper.Status.FAILURE) {
throw new PerformException.Builder()
.withActionDescription(getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new RuntimeException(String.format(
"Couldn't swipe from: %s,%s to: %s,%s precision: %s, %s . Swiper: %s "
+ "start coordinate provider: %s precision describer: %s. Tried %s times",
startCoordinates[0],
startCoordinates[1],
endCoordinates[0],
endCoordinates[1],
precision[0],
precision[1],
swiper,
startCoordinatesProvider,
precisionDescriber,
MAX_TRIES)))
.build();
}
}
@Test(expected = PerformException.class)
public void Verify_Throw_Prev_Step_When_Steps_Left() {
onView(withId(R.id.bt_prev)).perform(click());
}
/**
* Perform action of waiting for a specific view id.
* <p/>
* E.g.:
* onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15));
*
* @param viewId
* @param millis
* @return
*/
public static ViewAction waitId(final int viewId, final long millis) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isRoot();
}
@Override
public String getDescription() {
return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
}
@Override
public void perform(final UiController uiController, final View view) {
uiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + millis;
final Matcher<View> viewMatcher = withId(viewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
// found view with required ID
if (viewMatcher.matches(child)) {
return;
}
}
uiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
// timeout happens
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new TimeoutException())
.build();
}
};
}
/**
* Perform action of waiting for a specific view id.
* <p/>
* E.g.:
* onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15));
*
* @param viewId
* @param millis
* @return
*/
public static ViewAction waitId(final int viewId, final long millis) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isRoot();
}
@Override
public String getDescription() {
return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
}
@Override
public void perform(final UiController uiController, final View view) {
uiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + millis;
final Matcher<View> viewMatcher = withId(viewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
// found view with required ID
if (viewMatcher.matches(child)) {
return;
}
}
uiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
// timeout happens
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new TimeoutException())
.build();
}
};
}