下面列出了怎么用android.app.Instrumentation.ActivityResult的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void signIn() {
setupGoogleApiClientBridge(googleApiClientBridge, false);
Activity activity = activityRule.launchActivity(null);
ActivityResult result = createSignInResult();
intending(hasAction("com.google.android.gms.auth.GOOGLE_SIGN_IN")).respondWith(result);
onView(withId(R.id.signed_out_pane))
.check(matches(isDisplayed()));
TestUtil.matchToolbarTitle(activity.getString(R.string.app_name));
onView(withId(R.id.sign_in_button))
.perform(click());
onView(withId(R.id.signed_out_pane))
.check(matches(not(isDisplayed())));
TestUtil.matchToolbarTitle(activity.getString(R.string.title_word_sets));
Mockito.verify(googleApiClientBridge, Mockito.times(2)).isSignedIn();
}
@Override
public ActivityResult getActivityResultForIntent(Intent intent) {
checkState(isInitialized, "ResettingStubber must be initialized before calling this method");
checkNotNull(intent);
checkMain();
ListIterator<Pair<Matcher<Intent>, ActivityResultFunction>> reverseIterator =
intentResponsePairs.listIterator(intentResponsePairs.size());
while (reverseIterator.hasPrevious()) {
Pair<Matcher<Intent>, ActivityResultFunction> pair = reverseIterator.previous();
// We resolve the intent so that the toPackage matcher has the necessary information to match
// the intent.
if (pair.first.matches(resolveIntent(intent))) {
return pair.second.apply(intent);
}
}
return null;
}
@UiThreadTest
@Test
public void setActivityResultMultipleTime() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
ActivityResult result = new ActivityResult(10, intent);
ActivityResult duplicateResult =
new ActivityResult(100, new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")));
Matcher<Intent> matcher =
allOf(hasAction(equalTo(Intent.ACTION_VIEW)), hasData(hasHost(equalTo("www.android.com"))));
resettingStubber.setActivityResultForIntent(matcher, result);
resettingStubber.setActivityResultForIntent(matcher, duplicateResult);
assertEquals(
"Activity result didn't match expected value.",
resettingStubber.getActivityResultForIntent(intent),
duplicateResult);
assertEquals(
"Activity result didn't match expected value.",
resettingStubber.getActivityResultForIntent(intent),
duplicateResult);
}
@UiThreadTest
@Test
public void setActivityResultFunctionMultipleTime() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
ActivityResult result = new ActivityResult(10, intent);
ActivityResult duplicateResult =
new ActivityResult(100, new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")));
Matcher<Intent> matcher =
allOf(hasAction(equalTo(Intent.ACTION_VIEW)), hasData(hasHost(equalTo("www.android.com"))));
resettingStubber.setActivityResultFunctionForIntent(matcher, unused -> result);
resettingStubber.setActivityResultFunctionForIntent(matcher, unused -> duplicateResult);
assertEquals(
"Activity result didn't match expected value.",
resettingStubber.getActivityResultForIntent(intent),
duplicateResult);
assertEquals(
"Activity result didn't match expected value.",
resettingStubber.getActivityResultForIntent(intent),
duplicateResult);
}
/**
* This method can be used to retrieve the {@link ActivityResult} of an Activity that has called
* {@link Activity#setResult}. Usually, the result is handled in {@link Activity#onActivityResult}
* of the parent Activity, that has called {@link Activity#startActivityForResult}.
*
* <p>This method must <b>not</b> be called before {@code Activity.finish} was called or after the
* activity was already destroyed.
*
* <p>Note: This method assumes {@link Activity#setResult(int)} is called no later than in {@link
* Activity#onPause()}.
*
* @return the {@link ActivityResult} that was set most recently
* @throws IllegalStateException if the activity is not in finishing state.
*/
public ActivityResult getActivityResult() {
if (null == activityResult) {
// This is required if users manually called .finish() on their activity instead of using
// this.finishActivity(). Since .finish() is async there could be a case that our callback
// wasn't called just yet.
T hardActivityRef = activity.get();
checkNotNull(hardActivityRef, "Activity wasn't created yet or already destroyed!");
try {
runOnUiThread(
new Runnable() {
@Override
public void run() {
checkState(hardActivityRef.isFinishing(), "Activity is not finishing!");
setActivityResultForActivity(hardActivityRef);
}
});
} catch (Throwable throwable) {
throw new IllegalStateException(throwable);
}
}
return activityResult;
}
@Test
public void addImageToNote_ShowsThumbnailInUi() {
// Create an Activity Result which can be used to stub the camera Intent
ActivityResult result = createImageCaptureActivityResultStub();
// If there is an Intent with ACTION_IMAGE_CAPTURE, intercept the Intent and respond with
// a stubbed result.
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);
// Check thumbnail view is not displayed
onView(withId(R.id.add_note_image_thumbnail)).check(matches(not(isDisplayed())));
selectTakeImageFromMenu();
// Check that the stubbed thumbnail is displayed in the UI
onView(withId(R.id.add_note_image_thumbnail))
.perform(scrollTo()) // Scroll to thumbnail
.check(matches(allOf(
hasDrawable(), // Check ImageView has a drawable set with a custom matcher
isDisplayed())));
}
@Test
public void addImageToNote_ShowsThumbnailInUi() {
// Create an Activity Result which can be used to stub the camera Intent
ActivityResult result = createImageCaptureActivityResultStub();
// If there is an Intent with ACTION_IMAGE_CAPTURE, intercept the Intent and respond with
// a stubbed result.
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);
// Check thumbnail view is not displayed
onView(withId(R.id.add_note_image_thumbnail)).check(matches(not(isDisplayed())));
selectTakeImageFromMenu();
// Check that the stubbed thumbnail is displayed in the UI
onView(withId(R.id.add_note_image_thumbnail))
.perform(scrollTo()) // Scroll to thumbnail
.check(matches(allOf(
hasDrawable(), // Check ImageView has a drawable set with a custom matcher
isDisplayed())));
}
private void stubAccountPickerIntent() {
// Stub the account picker using Espresso intents.
// It requires the test devices to be signed in into at least 1 Google account.
Intent data = new Intent();
data.putExtra(AccountManager.KEY_ACCOUNT_NAME, mSelectedAccount.name);
ActivityResult result = new ActivityResult(Activity.RESULT_OK, data);
// The account picker intent is a bit special and it doesn't seem to have an Action or
// package, so we have to match it by some of the extra keys.
// This is not ideal but I couldn't find a better way.
intending(hasExtraWithKey("allowableAccountTypes"))
.respondWith(result);
}
@Before
public void setUp() throws Exception {
// Espresso will not launch our activity for us, we must launch it via ActivityScenario.launch.
ActivityScenario.launch(SendActivity.class);
// Once initialized, Intento will begin recording and providing stubbing for intents.
Intents.init();
// Stubbing to block all external intents
intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null));
}
@UiThreadTest
@Test
public void reset_getActivityResultForIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
ActivityResult result = new ActivityResult(10, intent);
resettingStubber.setActivityResultForIntent(any(Intent.class), result);
assertEquals(resettingStubber.getActivityResultForIntent(intent), result);
resettingStubber.reset();
resettingStubber.initialize();
assertEquals(null, resettingStubber.getActivityResultForIntent(intent));
}
@UiThreadTest
@Test
public void reset_getActivityResultFunctionForIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
ActivityResult result = new ActivityResult(10, intent);
resettingStubber.setActivityResultFunctionForIntent(any(Intent.class), unused -> result);
assertEquals(resettingStubber.getActivityResultForIntent(intent), result);
resettingStubber.reset();
resettingStubber.initialize();
assertEquals(null, resettingStubber.getActivityResultForIntent(intent));
}
@UiThreadTest
@Test
public void setActivityResultForIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
ActivityResult result = new ActivityResult(10, intent);
resettingStubber.setActivityResultForIntent(
allOf(hasAction(equalTo(Intent.ACTION_VIEW)), hasData(hasHost(equalTo("www.android.com")))),
result);
assertEquals(
"Activity Result Not Equal.", resettingStubber.getActivityResultForIntent(intent), result);
}
@UiThreadTest
@Test
public void setActivityResultFunctionForIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.android.com"));
ActivityResult result = new ActivityResult(10, intent);
resettingStubber.setActivityResultFunctionForIntent(
allOf(hasAction(equalTo(Intent.ACTION_VIEW)), hasData(hasHost(equalTo("www.android.com")))),
unused -> result);
assertEquals(
"Activity Result Not Equal.", resettingStubber.getActivityResultForIntent(intent), result);
}
@Test
public void externalIntent_WithResultStubbing_toPackage() {
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
intending(toPackage("com.android.contacts"))
.respondWith(new ActivityResult(Activity.RESULT_OK, resultData));
pick(phoneNumber);
}
@Test
public void externalIntent_WithResultStubbing_hasAction() {
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
intending(hasAction("android.intent.action.PICK"))
.respondWith(new ActivityResult(Activity.RESULT_OK, resultData));
pick(phoneNumber);
}
@Test
public void externalIntents_WithResultStubbingMultiple_toPackage() {
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
intending(toPackage("com.android.contacts"))
.respondWith(new ActivityResult(Activity.RESULT_OK, resultData));
Intent resultData2 = new Intent();
String phoneNumber2 = "987-654-3210";
resultData2.putExtra("phone", phoneNumber2);
intending(toPackage("com.android.contacts"))
.respondWith(new ActivityResult(Activity.RESULT_OK, resultData2));
pick(phoneNumber2);
}
@Test
public void externalIntent_WithResultStubbingCallable() {
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
TestActivityResultFunction resultCallable =
new TestActivityResultFunction(new ActivityResult(Activity.RESULT_OK, resultData));
intending(toPackage("com.android.contacts")).respondWithFunction(resultCallable);
pick(phoneNumber);
assertThat(resultCallable.wasCalled).isTrue();
}
@Test
public void internalIntentStubbing() {
intending(isInternal()).respondWith(new ActivityResult(Activity.RESULT_OK, null));
clickToDisplayActivity();
// Validate that we're still on the same screen (i.e. the intent to the DisplayActivity was
// stubbed)
onView(withId(R.id.send_button)).check(matches(isDisplayed()));
}
/**
* Returns a matcher that verifies that the {@code resultCode} of a given {@link ActivityResult}
* matches the given code
*/
public static Matcher<? super ActivityResult> hasResultCode(final int resultCode) {
return new TypeSafeMatcher<ActivityResult>(ActivityResult.class) {
@Override
public void describeTo(Description description) {
description.appendText("has result code " + resultCode);
}
@Override
protected boolean matchesSafely(ActivityResult activityResult) {
return activityResult.getResultCode() == resultCode;
}
};
}
@Test
public void successHasResultData() {
Intent intent = new Intent(Intent.ACTION_MAIN);
ActivityResult activityResult = new ActivityResult(1, intent);
assertThat(
ActivityResultMatchers.hasResultData(isSameIntent(intent)).matches(activityResult),
is(true));
}
@Test
public void failureHasResultData() {
Intent intent = new Intent(Intent.ACTION_MAIN);
ActivityResult activityResult = new ActivityResult(1, intent);
assertThat(
ActivityResultMatchers.hasResultData(isSameIntent(new Intent(Intent.ACTION_VIEW)))
.matches(activityResult),
is(false));
}
@Test
@UiThreadTest
public void shouldReturnActivityResult() {
// We need to use a real Activity (no mock) here in order to capture the result.
// The Activity we use is android.app.Activity which exists on all API levels.
Activity activity = rule.getActivity();
activity.setResult(Activity.RESULT_OK, new Intent(Intent.ACTION_VIEW));
activity.finish(); // must be called on the UI Thread
ActivityResult activityResult = rule.getActivityResult();
assertNotNull(activityResult);
assertEquals(Activity.RESULT_OK, activityResult.getResultCode());
assertEquals(Intent.ACTION_VIEW, activityResult.getResultData().getAction());
}
@Test
public void shouldReturnActivityResult_withActivityFinish() {
// We need to use a real Activity (no mock) here in order to capture the result.
// The Activity we use is android.app.Activity which exists on all API levels.
Activity activity = rule.getActivity();
activity.setResult(Activity.RESULT_OK, new Intent(Intent.ACTION_VIEW));
rule.finishActivity();
ActivityResult activityResult = rule.getActivityResult();
assertNotNull(activityResult);
assertEquals(Activity.RESULT_OK, activityResult.getResultCode());
assertEquals(Intent.ACTION_VIEW, activityResult.getResultData().getAction());
}
@Before
public void setUp() throws Exception {
mIntentStubber =
new IntentStubber() {
@Override
public ActivityResult getActivityResultForIntent(Intent intent) {
return null;
}
};
}
/**
* Waits for the activity result to be available until the timeout and returns the result.
*
* @throws NullPointerException if the result doesn't become available after the timeout
* @return activity result of which {@link #startActivity} starts
*/
public ActivityResult getActivityResult() {
try {
latch.await(ActivityLifecycleTimeout.getMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.i(TAG, "Waiting activity result was interrupted", e);
}
checkNotNull(
activityResult,
"onActivityResult never be called after %d milliseconds",
ActivityLifecycleTimeout.getMillis());
return activityResult;
}
private ActivityResult createSignInResult() {
return new ActivityResult(Activity.RESULT_OK, null);
}
public ActivityResult execStartActivity() {
return InstrumentationHook.this.mBase.execStartActivity(this.val$who, this.val$contextThread, this.val$token, this.val$target, this.val$intent, this.val$requestCode);
}
public ActivityResult execStartActivity() {
return InstrumentationHook.this.mBase.execStartActivity(this.val$who, this.val$contextThread, this.val$token, this.val$target, this.val$intent, this.val$requestCode, this.val$options);
}
public ActivityResult execStartActivity() {
return InstrumentationHook.this.mBase.execStartActivity(this.val$who, this.val$contextThread, this.val$token, this.val$target, this.val$intent, this.val$requestCode);
}
public ActivityResult execStartActivity() {
return InstrumentationHook.this.mBase.execStartActivity(this.val$who, this.val$contextThread, this.val$token, this.val$target, this.val$intent, this.val$requestCode, this.val$options);
}