下面列出了io.reactivex.rxjava3.functions.Function#androidx.test.espresso.IdlingRegistry 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void smartcarddemo_nfc() throws Exception {
//wait for completion, or timeout in ElapsedTimeIdlingResource(X) where X is in milliseconds
ElapsedTimeIdlingResource iresLogRead = new ElapsedTimeIdlingResource(3000);
//navigate to Smartcard Demo
onView(withId(R.id.nav_view))
.perform(NavigationViewActions.navigateTo(R.id.smartcard_fragment));
IdlingRegistry.getInstance().register(iresLogRead);
//Test pass if "signature is valid" is shown; otherwise, test fails.
onView(withId(R.id.log))
.check(matches(withSubstring("Signature is valid")));
IdlingRegistry.getInstance().unregister(iresLogRead);
}
@Before
public void beforeTest() {
try {
Timber.e("@Before: register idle resource");
idlingResource = new OnMapReadyIdlingResource(rule.getActivity());
IdlingRegistry.getInstance().register(idlingResource);
onView(withId(android.R.id.content)).check(matches(isDisplayed()));
mapboxMap = idlingResource.getMapboxMap();
buildingPlugin = rule.getActivity().getBuildingPlugin();
} catch (IdlingResourceTimeoutException idlingResourceTimeoutException) {
Timber.e("Idling resource timed out. Couldn't not validate if map is ready.");
throw new RuntimeException("Could not start executeLocationLayerTest for "
+ this.getClass().getSimpleName() + ".\n The ViewHierarchy doesn't contain a view with resource id ="
+ "R.id.mapView or \n the Activity doesn't contain an instance variable with a name equal to mapboxMap.\n");
}
}
@Before
public void setupDatePickerDialogForSwiping() {
CalendarConstraints calendarConstraints =
new CalendarConstraints.Builder()
.setStart(START.timeInMillis)
.setEnd(END.timeInMillis)
.setOpenAt(OPEN_AT.timeInMillis)
.build();
FragmentManager fragmentManager = activityTestRule.getActivity().getSupportFragmentManager();
String tag = "Date DialogFragment";
dialogFragment =
MaterialDatePicker.Builder.datePicker().setCalendarConstraints(calendarConstraints).build();
dialogFragment.show(fragmentManager, tag);
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
IdlingRegistry.getInstance()
.register(
new RecyclerIdlingResource(
dialogFragment.getView().findViewWithTag(MaterialCalendar.MONTHS_VIEW_GROUP_TAG)));
listenerIdlingResource = new ListenerIdlingResource();
}
public void register() throws Exception {
resource = new CountingIdlingResource("counter");
IdlingRegistry.getInstance().register(resource);
IdlingUIActivity.listener =
new IdlingUIActivity.Listener() {
@Override
public void onLoadStarted() {
resource.increment();
}
@Override
public void onLoadFinished() {
resource.decrement();
}
};
}
@Override
public final void perform(UiController uiController, View view) {
DrawerLayout drawer = (DrawerLayout) view;
if (!checkAction().matches(drawer)) {
return;
}
Object tag = drawer.getTag(TAG);
IdlingDrawerListener idlingListener;
if (tag instanceof IdlingDrawerListener) {
idlingListener = (IdlingDrawerListener) tag;
} else {
idlingListener = new IdlingDrawerListener();
drawer.setTag(TAG, idlingListener);
drawer.addDrawerListener(idlingListener);
IdlingRegistry.getInstance().register(idlingListener);
}
performAction(uiController, drawer);
uiController.loopMainThreadUntilIdle();
IdlingRegistry.getInstance().unregister(idlingListener);
drawer.removeDrawerListener(idlingListener);
drawer.setTag(TAG, null);
}
@Override
public boolean onCreate() {
if (EnvironmentChecks.testsAreRunning()) {
IdlingRegistry.getInstance().register(new BusyBeeIdlingResource(BusyBee.singleton()));
}
return true;
}
@Before
public void setUp() {
idlingResource = IdlingResourceManager.getInstance();
IdlingRegistry.getInstance().register(idlingResource);
onView(withId(R.id.reset_frc_button)).perform(click());
}
public void teardown() throws IOException {
//if test fail, unregister all resources
for (IdlingResource resource : registeredResources) {
IdlingRegistry.getInstance().unregister(resource);
}
activityRule.finishActivity();
}
@Before
public void beforeTest() {
try {
Timber.e("@Before %s: register idle resource", testName.getMethodName());
IdlingRegistry.getInstance().register(idlingResource = new OnMapReadyIdlingResource(rule.getActivity()));
Espresso.onIdle();
mapboxMap = idlingResource.getMapboxMap();
} catch (IdlingResourceTimeoutException idlingResourceTimeoutException) {
throw new RuntimeException(String.format("Could not start %s test for %s.\n Either the ViewHierarchy doesn't "
+ "contain a view with resource id = R.id.mapView or \n the hosting Activity wasn't in an idle state.",
testName.getMethodName(),
getActivityClass().getSimpleName())
);
}
}
/**
* Returns a function which wraps the supplied {@link Scheduler} in one which notifies Espresso as
* to whether it is currently executing work or not.
* <p>
* Note: Work scheduled in the future does not mark the idling resource as busy.
*/
@SuppressWarnings("ConstantConditions") // Public API guarding.
@CheckResult @NonNull
public static Function<Supplier<Scheduler>, Scheduler> create(@NonNull final String name) {
if (name == null) throw new NullPointerException("name == null");
return delegate -> {
IdlingResourceScheduler scheduler =
new DelegatingIdlingResourceScheduler(delegate.get(), name);
IdlingRegistry.getInstance().register(scheduler);
return scheduler;
};
}
/**
* Returns a function which wraps the supplied {@link Scheduler} in one which notifies Espresso as
* to whether it is currently executing work or not.
* <p>
* Note: Work scheduled in the future does not mark the idling resource as busy.
*/
@SuppressWarnings("ConstantConditions") // Public API guarding.
@CheckResult @NonNull
public static Function<Callable<Scheduler>, Scheduler> create(@NonNull final String name) {
if (name == null) throw new NullPointerException("name == null");
return new Function<Callable<Scheduler>, Scheduler>() {
@Override public Scheduler apply(Callable<Scheduler> delegate) throws Exception {
IdlingResourceScheduler scheduler =
new DelegatingIdlingResourceScheduler(delegate.call(), name);
IdlingRegistry.getInstance().register(scheduler);
return scheduler;
}
};
}
@Test
public void testFabButtonAndList() {
IdlingResource ir = new RecyclerViewScrollingIdlingResource((RecyclerView) activity.findViewById(R.id.list));
IdlingRegistry.getInstance().register(ir);
Matcher listMatcher = withId(R.id.list);
onView(listMatcher).perform(smoothScrollTo(12));
onView(withId(R.id.fab)).perform(click());
onView(listMatcher).perform(smoothScrollTo(0));
onView(withId(R.id.fab)).perform(click());
IdlingRegistry.getInstance().unregister(ir);
}
@Before
public void startWebServer() throws Exception {
webServer = new MockWebServer();
webServer.enqueue(createMockResponseFromAsset("tab1.html"));
webServer.enqueue(createMockResponseFromAsset("tab2.html"));
webServer.enqueue(createMockResponseFromAsset("tab3.html"));
webServer.enqueue(createMockResponseFromAsset("tab2.html"));
webServer.start();
loadingIdlingResource = new SessionLoadedIdlingResource();
IdlingRegistry.getInstance().register(loadingIdlingResource);
}
/**
* Tests that the indicator animation still functions as intended when modifying the animator's
* update listener, instead of removing/recreating the animator itself.
*/
@Test
public void testIndicatorAnimator_worksAfterReplacingUpdateListener() throws Throwable {
activityTestRule.runOnUiThread(
() -> activityTestRule.getActivity().setContentView(R.layout.design_tabs_items));
final TabLayout tabs = activityTestRule.getActivity().findViewById(R.id.tabs);
onView(withId(R.id.tabs)).perform(setTabMode(TabLayout.MODE_FIXED));
final TabLayoutScrollIdlingResource idler = new TabLayoutScrollIdlingResource(tabs);
IdlingRegistry.getInstance().register(idler);
// We need to click a tab once to set up the indicator animation (so that it's not still null).
onView(withId(R.id.tabs)).perform(selectTab(1));
// Select new tab. This action should modify the listener on the animator.
onView(withId(R.id.tabs)).perform(selectTab(2));
onView(withId(R.id.tabs))
.check(
(view, notFoundException) -> {
if (view == null) {
throw notFoundException;
}
TabLayout tabs1 = (TabLayout) view;
int tabTwoLeft = tabs1.getTabAt(/* index= */ 2).view.getLeft();
int tabTwoRight = tabs1.getTabAt(/* index= */ 2).view.getRight();
assertEquals(tabs1.slidingTabIndicator.indicatorLeft, tabTwoLeft);
assertEquals(tabs1.slidingTabIndicator.indicatorRight, tabTwoRight);
});
IdlingRegistry.getInstance().unregister(idler);
}
@Before
public void setUp() throws Throwable {
activityTestRule = getActivityTestRule();
final Context context = activityTestRule.getActivity();
if (context == null)
throw new RuntimeException("Could not get context. Maybe activity failed to start?");
Utils.clearSharedPreferences(context);
//Prevent drawer from opening when we start a new activity
Utils.setLearnedAboutDrawerPreference(context, true);
//Allow each test to change the shared preferences
setSharedPreferences(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean useEventServer = prefs.getBoolean(HostFragmentManualConfiguration.HOST_USE_EVENT_SERVER, false);
hostInfo = Database.addHost(context, server.getHostName(),
HostConnection.PROTOCOL_TCP, HostInfo.DEFAULT_HTTP_PORT,
server.getPort(), useEventServer, kodiMajorVersion);
loaderIdlingResource = new LoaderIdlingResource(activityTestRule.getActivity().getSupportLoaderManager());
IdlingRegistry.getInstance().register(loaderIdlingResource);
Utils.disableAnimations(context);
Utils.setupMediaProvider(context);
Database.fill(hostInfo, context, context.getContentResolver());
Utils.switchHost(context, activityTestRule.getActivity(), hostInfo);
//Relaunch the activity for the changes (Host selection, preference changes, and database fill) to take effect
activityTestRule.finishActivity();
activityTestRule.launchActivity(new Intent());
}
@After
public void tearDown() throws Exception {
if ( loaderIdlingResource != null )
IdlingRegistry.getInstance().unregister(loaderIdlingResource);
applicationHandler.reset();
playerHandler.reset();
Context context = activityTestRule.getActivity();
Database.flush(context.getContentResolver());
Utils.enableAnimations(context);
}
/**
* Only called from test, creates and returns a new {@link SimpleIdlingResource}.
*/
@VisibleForTesting
boolean registerIdlingResource() {
if (idlingResource == null) {
idlingResource = new SimpleIdlingResource();
}
return IdlingRegistry.getInstance().register(idlingResource);
}
@Provides
public IdleNotifier<IdleNotificationCallback> provideDynamicNotifer(
IdlingResourceRegistry dynamicRegistry) {
// Since a dynamic notifier will be created for each Espresso interaction this is a good time
// to sync the IdlingRegistry with IdlingResourceRegistry.
dynamicRegistry.sync(
IdlingRegistry.getInstance().getResources(), IdlingRegistry.getInstance().getLoopers());
return dynamicRegistry.asIdleNotifier();
}
private void tryToCloseKeyboard(View view, UiController uiController) throws TimeoutException {
InputMethodManager imm =
(InputMethodManager)
getRootActivity(uiController).getSystemService(Context.INPUT_METHOD_SERVICE);
CloseKeyboardIdlingResult idlingResult =
new CloseKeyboardIdlingResult(new Handler(Looper.getMainLooper()));
IdlingRegistry.getInstance().register(idlingResult);
try {
if (!imm.hideSoftInputFromWindow(view.getWindowToken(), 0, idlingResult)) {
Log.w(TAG, "Attempting to close soft keyboard, while it is not shown.");
return;
}
// set 2 second timeout
idlingResult.scheduleTimeout(2000);
uiController.loopMainThreadUntilIdle();
if (idlingResult.timedOut) {
throw new TimeoutException("Wait on operation result timed out.");
}
} finally {
IdlingRegistry.getInstance().unregister(idlingResult);
}
if (idlingResult.result != InputMethodManager.RESULT_UNCHANGED_HIDDEN
&& idlingResult.result != InputMethodManager.RESULT_HIDDEN) {
String error =
"Attempt to close the soft keyboard did not result in soft keyboard to be hidden."
+ " resultCode = "
+ idlingResult.result;
Log.e(TAG, error);
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new RuntimeException(error))
.build();
}
}
/**
* Use {@link ActivityScenario to launch and get access to the activity.
* {@link ActivityScenario#onActivity(ActivityScenario.ActivityAction)} provides a thread-safe
* mechanism to access the activity.
*/
@Before
public void registerIdlingResource() {
ActivityScenario activityScenario = ActivityScenario.launch(MainActivity.class);
activityScenario.onActivity(new ActivityScenario.ActivityAction<MainActivity>() {
@Override
public void perform(MainActivity activity) {
mIdlingResource = activity.getIdlingResource();
// To prove that the test fails, omit this call:
IdlingRegistry.getInstance().register(mIdlingResource);
}
});
}
@Before
public void setup() {
IdlingPolicies.setMasterPolicyTimeout(1, TimeUnit.MINUTES);
IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.MINUTES);
Intent intent = new Intent();
mActivityTestRule.launchActivity(intent);
myActivity = (MyActivity) mActivityTestRule.getActivity();
IdlingRegistry.getInstance().register(myActivity.idlingResource);
}
private void clearIdlingResources() {
IdlingRegistry.getInstance().unregister(idlingResource);
}
@Before
public void setUpIdlingResources() {
loadingIdlingResource = new SessionLoadedIdlingResource();
IdlingRegistry.getInstance().register(loadingIdlingResource);
}
@After
public void tearDownIdlingResources() {
IdlingRegistry.getInstance().unregister(loadingIdlingResource);
}
protected void idlingBlock(IdlingResource idlingResource, Exceptionable runnable) throws Exception {
IdlingRegistry.getInstance().register(idlingResource);
registeredResources.add(idlingResource);
runnable.run();
IdlingRegistry.getInstance().unregister(idlingResource);
}
@After
public void afterTest() {
Timber.e("@After: unregister idle resource");
IdlingRegistry.getInstance().unregister(idlingResource);
}
@After
public void afterTest() {
Timber.e("@After test: unregister idle resource");
IdlingRegistry.getInstance().unregister(idlingResource);
}
@Override public Scheduler getComputationScheduler() {
Scheduler delegate = createComputationScheduler();
IdlingResourceScheduler scheduler = RxIdler.wrap(delegate, "RxJava 1.x Computation Scheduler");
IdlingRegistry.getInstance().register(scheduler);
return scheduler;
}
@Override public Scheduler getIOScheduler() {
Scheduler delegate = createIoScheduler();
IdlingResourceScheduler scheduler = RxIdler.wrap(delegate, "RxJava 1.x IO Scheduler");
IdlingRegistry.getInstance().register(scheduler);
return scheduler;
}
@Override public Scheduler getNewThreadScheduler() {
Scheduler delegate = createNewThreadScheduler();
IdlingResourceScheduler scheduler = RxIdler.wrap(delegate, "RxJava 1.x New Thread Scheduler");
IdlingRegistry.getInstance().register(scheduler);
return scheduler;
}