Я черпал вдохновение у Анатолия, но вместо использования методов из View.class я все еще использую только ViewMatchers.
/**
* {@link IdlingResource} that idles until a {@link View} condition is fulfilled.
*/
public class ViewIdlingResource implements IdlingResource {
private final Matcher<View> viewMatcher;
private final Matcher<View> idleMatcher;
private ResourceCallback resourceCallback;
/**
* Constructor.
*
* @param viewMatcher The matcher to find the view.
* @param idlerMatcher The matcher condition to be fulfilled to be considered idle.
*/
public ViewIdlingResource(final Matcher<View> viewMatcher, Matcher<View> idlerMatcher) {
this.viewMatcher = viewMatcher;
this.idleMatcher = idlerMatcher;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIdleNow() {
View view = getView(viewMatcher);
boolean isIdle = idleMatcher.matches(view);
if (isIdle && resourceCallback != null) {
resourceCallback.onTransitionToIdle();
}
return isIdle;
}
/**
* {@inheritDoc}
*/
@Override
public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
this.resourceCallback = resourceCallback;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this + viewMatcher.toString();
}
/**
* Tries to find the view associated with the given {@link Matcher<View>}.
*/
private static View getView(Matcher<View> viewMatcher) {
try {
ViewInteraction viewInteraction = onView(viewMatcher);
Field finderField = viewInteraction.getClass().getDeclaredField("viewFinder");
finderField.setAccessible(true);
ViewFinder finder = (ViewFinder) finderField.get(viewInteraction);
return finder.getView();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
А как использовать бездельник в вашем тестовом примере, я пропускаю ViewMatchers.isDisplayed () будет моим ожидаемым условием в idler.
private void waitUntilViewIsDisplayed(Matcher<View> matcher) {
IdlingResource idlingResource = new ViewIdlingResource(matcher, isDisplayed());
try {
IdlingRegistry.getInstance().register(idlingResource);
// First call to onView is to trigger the idler.
onView(withId(0)).check(doesNotExist());
} finally {
IdlingRegistry.getInstance().unregister(idlingResource);
}
}
С этим вы можете передать любой Matcher.class в конструктор ViewIdlingResource, чтобы он стал обязательным условием для представления, найденного параметром viewMatcher.