下面列出了怎么用android.support.test.rule.ActivityTestRule的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
@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;
}
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
});
}
@Override
protected void init(ActivityTestRule activityTestRule)
{
super.init(activityTestRule);
userRepo = (MemoryUserRepository) app.getUserRepository();
dataRepo = (MemoryDataRepository) app.getDataRepository();
}
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();
}
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);
}
static void waitTillCreated(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
throws Throwable {
waitTillState(owner, activityRule, CREATED);
}
static void waitTillStarted(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
throws Throwable {
waitTillState(owner, activityRule, STARTED);
}
static void waitTillResumed(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
throws Throwable {
waitTillState(owner, activityRule, RESUMED);
}
static void waitTillDestroyed(final LifecycleOwner owner, ActivityTestRule<?> activityRule)
throws Throwable {
waitTillState(owner, activityRule, DESTROYED);
}
@Test
public void ActivityTestRule() {
TestActivity mTestActivity = mActivityTestRule.getActivity();
}
@Override
ActivityTestRule getActivityRule() {
return activityRule;
}
@Override
ActivityTestRule getActivityRule() {
return activityRule;
}
protected void init(ActivityTestRule activityTestRule)
{
app = (TestMyApp) activityTestRule.getActivity().getApplication();
}
public TestActivityRepoList() {
super(new ActivityTestRule<>(ActivityRepoList.class, true, false));
}
protected AbstractRobotiumTestCase(final ActivityTestRule<TypeActivity> poActivityTestRule) {
mActivityTestRule = poActivityTestRule;
}
public TestActivityRepoList() {
super(new ActivityTestRule<>(ActivityMain.class, true, false));
}
protected AbstractRobotiumTestCase(final ActivityTestRule<TypeActivity> poActivityTestRule) {
mActivityTestRule = poActivityTestRule;
}
public CameraViewTest() {
rule = new ActivityTestRule<>(CameraViewActivity.class);
}
public AssetTestRule(DaoSessionResource daoSessionResource, ActivityTestRule activityRule) {
this.daoSessionResource = daoSessionResource;
this.activityRule = activityRule;
testFiles = new ArrayList<>();
isTestAssetSet = false;
}
public TaskTemplateRule(DaoSessionResource daoSessionResource, ActivityTestRule activityRule) {
this.daoSessionResource = daoSessionResource;
this.activityRule = activityRule;
}
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();
}
public PostMessageTest() {
mActivityTestRule = new ActivityTestRule<TestActivity>(TestActivity.class);
mServiceRule = new ServiceTestRule();
}
/**
* Rotate the device to landscape and back.
*/
public void rotateDevice(ActivityTestRule activityRule)
{
rotateDevice(activityRule, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
rotateDevice(activityRule, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/**
* 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);
}