类android.support.test.rule.ActivityTestRule源码实例Demo

下面列出了怎么用android.support.test.rule.ActivityTestRule的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: material-activity-chooser   文件: ActivityUtils.java
/**
 * Gets an instance of the currently active (displayed) activity.
 * @param activityTestRule test rule
 * @param <T> activity class
 * @return activity instance
 */
public static  <T extends Activity> T getCurrentActivity(@NonNull ActivityTestRule activityTestRule) {
    getInstrumentation().waitForIdleSync();
    final Activity[] activity = new Activity[1];
    try {
        activityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                java.util.Collection<Activity> activites = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
                activity[0] = Iterables.getOnlyElement(activites);
            }});
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    //noinspection unchecked
    return (T) activity[0];
}
 
public static void Disconnect(ActivityTestRule<SnippetListActivity> snippetListActivityTestRule) {
    SnippetListActivity snippetListActivity = snippetListActivityTestRule.launchActivity(null);

    openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());

    // Espresso can't find menu items by id. We'll use the text property.
    onView(withText(R.string.disconnect_menu_item))
            .perform(click());

    intended(allOf(
            hasComponent(hasShortClassName(".SignInActivity")),
            toPackage("com.microsoft.graph.snippets")
    ));

    snippetListActivity.finish();
}
 
public static List<Integer> getSnippetsIndexes(ActivityTestRule<SnippetListActivity> snippetListActivityRule) {
    SnippetListActivity snippetListActivity = snippetListActivityRule.launchActivity(null);

    ListAdapter listAdapter = getListAdapter(snippetListActivity);
    int numItems = listAdapter.getCount();

    List<Integer> snippetIndexes = new ArrayList<>();

    // Get the index of items in the adapter that
    // are actual snippets and not categories, which don't have a Url
    for (int i = 0; i < numItems; i++) {
        if(((AbstractSnippet)listAdapter.getItem(i)).getUrl() != null) {
            snippetIndexes.add(i);
        }
    }

    snippetListActivity.finish();

    return snippetIndexes;
}
 
源代码4 项目: android_9.0.0_r45   文件: TestUtils.java
@SuppressWarnings("unchecked")
static <T extends Activity> T recreateActivity(final T activity, ActivityTestRule rule)
        throws Throwable {
    ActivityMonitor monitor = new ActivityMonitor(
            activity.getClass().getCanonicalName(), null, false);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.addMonitor(monitor);
    rule.runOnUiThread(activity::recreate);
    T result;

    // this guarantee that we will reinstall monitor between notifications about onDestroy
    // and onCreate
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (monitor) {
        do {
            // the documetation says "Block until an Activity is created
            // that matches this monitor." This statement is true, but there are some other
            // true statements like: "Block until an Activity is destoyed" or
            // "Block until an Activity is resumed"...

            // this call will release synchronization monitor's monitor
            result = (T) monitor.waitForActivityWithTimeout(TIMEOUT_MS);
            if (result == null) {
                throw new RuntimeException("Timeout. Failed to recreate an activity");
            }
        } while (result == activity);
    }
    return result;
}
 
源代码5 项目: android_9.0.0_r45   文件: TestUtils.java
static void waitTillState(final LifecycleOwner owner, ActivityTestRule<?> activityRule,
        Lifecycle.State state)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(1);
    activityRule.runOnUiThread(() -> {
        Lifecycle.State currentState = owner.getLifecycle().getCurrentState();
        if (currentState == state) {
            latch.countDown();
        } else {
            owner.getLifecycle().addObserver(new LifecycleObserver() {
                @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
                public void onStateChanged(LifecycleOwner provider) {
                    if (provider.getLifecycle().getCurrentState() == state) {
                        latch.countDown();
                        provider.getLifecycle().removeObserver(this);
                    }
                }
            });
        }
    });
    boolean latchResult = latch.await(1, TimeUnit.MINUTES);
    assertThat("expected " + state + " never happened. Current state:"
                    + owner.getLifecycle().getCurrentState(), latchResult, is(true));

    // wait for another loop to ensure all observers are called
    activityRule.runOnUiThread(() -> {
        // do nothing
    });
}
 
源代码6 项目: DebugRank   文件: RepositoryBehaviorTest.java
@Override
protected void init(ActivityTestRule activityTestRule)
{
    super.init(activityTestRule);

    userRepo = (MemoryUserRepository) app.getUserRepository();
    dataRepo = (MemoryDataRepository) app.getDataRepository();
}
 
源代码7 项目: unity-ads-android   文件: LifecycleListenerTest.java
protected Activity waitForActivityStart (final ActivityTestRule rule) {
	final ConditionVariable cv = new ConditionVariable();
	WebViewApp.setCurrentApp(new WebViewApp() {
		private boolean allowEvents = false;

		@Override
		public boolean sendEvent(Enum eventCategory, Enum eventId, Object... params) {
			if ("CREATED".equals(eventId.name())) {
				allowEvents = true;
			}

			if (allowEvents && params[0].equals("com.unity3d.ads.test.legacy.LifecycleListenerTestActivity")) {
				DeviceLog.debug(eventId.name() + " " + params[0]);

				EVENTS.add(eventId);
				EVENT_PARAMS.add(params);
				EVENT_COUNT++;
			}

			return true;
		}
	});

	new Thread(new Runnable() {
		@Override
		public void run() {
			rule.launchActivity(new Intent());
			cv.open();
		}
	}).start();

	boolean success = cv.block(30000);
	return rule.getActivity();
}
 
源代码8 项目: medic-gateway   文件: InstrumentationTestUtils.java
public static void recreateActivityFor(final ActivityTestRule testRule) {
	getInstrumentation().runOnMainSync(new Runnable() {
		public void run() {
			testRule.getActivity().recreate();
		}
	});
}
 
public ActivityFullLifecycleTest(Class<? extends Activity> activityClass) {
    //noinspection unchecked
    activityTestRule = new ActivityTestRule(activityClass);
}
 
源代码10 项目: android_9.0.0_r45   文件: TestUtils.java
static void waitTillCreated(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
        throws Throwable {
    waitTillState(owner, activityRule, CREATED);
}
 
源代码11 项目: android_9.0.0_r45   文件: TestUtils.java
static void waitTillStarted(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
        throws Throwable {
    waitTillState(owner, activityRule, STARTED);
}
 
源代码12 项目: android_9.0.0_r45   文件: TestUtils.java
static void waitTillResumed(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
        throws Throwable {
    waitTillState(owner, activityRule, RESUMED);
}
 
源代码13 项目: android_9.0.0_r45   文件: TestUtils.java
static void waitTillDestroyed(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
        throws Throwable {
    waitTillState(owner, activityRule, DESTROYED);
}
 
源代码14 项目: Awesome-WanAndroid   文件: TestActivityTest.java
@Test
public void ActivityTestRule() {
    TestActivity mTestActivity = mActivityTestRule.getActivity();
}
 
@Override
ActivityTestRule getActivityRule() {
    return activityRule;
}
 
@Override
ActivityTestRule getActivityRule() {
    return activityRule;
}
 
源代码17 项目: DebugRank   文件: BaseBehaviorTest.java
protected void init(ActivityTestRule activityTestRule)
{
    app = (TestMyApp) activityTestRule.getActivity().getApplication();
}
 
源代码18 项目: AndroidStarter   文件: TestActivityRepoList.java
public TestActivityRepoList() {
    super(new ActivityTestRule<>(ActivityRepoList.class, true, false));
}
 
源代码19 项目: AndroidStarter   文件: AbstractRobotiumTestCase.java
protected AbstractRobotiumTestCase(final ActivityTestRule<TypeActivity> poActivityTestRule) {
    mActivityTestRule = poActivityTestRule;
}
 
源代码20 项目: AndroidStarterAlt   文件: TestActivityRepoList.java
public TestActivityRepoList() {
    super(new ActivityTestRule<>(ActivityMain.class, true, false));
}
 
protected AbstractRobotiumTestCase(final ActivityTestRule<TypeActivity> poActivityTestRule) {
    mActivityTestRule = poActivityTestRule;
}
 
源代码22 项目: cameraview   文件: CameraViewTest.java
public CameraViewTest() {
    rule = new ActivityTestRule<>(CameraViewActivity.class);
}
 
源代码23 项目: friendly-plans   文件: AssetTestRule.java
public AssetTestRule(DaoSessionResource daoSessionResource, ActivityTestRule activityRule) {
    this.daoSessionResource = daoSessionResource;
    this.activityRule = activityRule;
    testFiles = new ArrayList<>();
    isTestAssetSet = false;
}
 
源代码24 项目: friendly-plans   文件: TaskTemplateRule.java
public TaskTemplateRule(DaoSessionResource daoSessionResource, ActivityTestRule activityRule) {
    this.daoSessionResource = daoSessionResource;
    this.activityRule = activityRule;
}
 
源代码25 项目: friendly-plans   文件: PlanTemplateRule.java
public PlanTemplateRule(DaoSessionResource daoSessionResource, ActivityTestRule activityRule) {
    this.daoSessionResource = daoSessionResource;
    this.activityRule = activityRule;
}
 
public static void AzureADSignIn(String username, String password, ActivityTestRule<SignInActivity> signInActivityTestRule) throws InterruptedException {
    SignInActivity signInActivity = signInActivityTestRule.launchActivity(null);

    onView(withId(R.id.o365_signin)).perform(click());

    try {
        onWebView()
                .withElement(findElement(Locator.ID, USER_ID_TEXT_ELEMENT))
                .perform(clearElement())
                // Enter text into the input element
                .perform(DriverAtoms.webKeys(username))
                // Set focus on the username input text
                // The form validates the username when this field loses focus
                .perform(webClick())
                .withElement(findElement(Locator.ID, PASSWORD_TEXT_ELEMENT))
                // Now we force focus on this element to make
                // the username element to lose focus and validate
                .perform(webClick())
                .perform(clearElement())
                // Enter text into the input element
                .perform(DriverAtoms.webKeys(password));

        Thread.sleep(2000, 0);

        onWebView()
                .withElement(findElement(Locator.ID, SIGN_IN_BUTTON_ELEMENT))
                .perform(webClick());
    } catch (NoMatchingViewException ex) {
        // If user is already logged in, the flow will go directly to SnippetListActivity
    } finally {
        Thread.sleep(2000, 0);
    }

    // Finally, verify that SnippetListActivity is on top
    intended(allOf(
            hasComponent(hasShortClassName(".SnippetListActivity")),
            toPackage("com.microsoft.graph.snippets")
    ));

    signInActivity.finish();
}
 
private int getActualSnippetsCount(ActivityTestRule<SnippetListActivity> snippetListActivityRule) {
    List<Integer> actualSnippetsIndexes = getSnippetsIndexes(snippetListActivityRule);
    return actualSnippetsIndexes.size();
}
 
源代码28 项目: custom-tabs-client   文件: PostMessageTest.java
public PostMessageTest() {
    mActivityTestRule = new ActivityTestRule<TestActivity>(TestActivity.class);
    mServiceRule = new ServiceTestRule();
}
 
源代码29 项目: SuntimesWidget   文件: SuntimesActivityTestBase.java
/**
 * Rotate the device to landscape and back.
 */
public void rotateDevice(ActivityTestRule activityRule)
{
    rotateDevice(activityRule, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    rotateDevice(activityRule, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
 
源代码30 项目: SuntimesWidget   文件: SuntimesActivityTestBase.java
/**
 * Rotate to given orientation.
 * @param orientation ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE | ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
 */
public void rotateDevice(ActivityTestRule activityRule, int orientation )
{
    activityRule.getActivity().setRequestedOrientation(orientation);
}
 
 类所在包
 类方法
 同包方法