android.app.Instrumentation.ActivityResult Java Examples

The following examples show how to use android.app.Instrumentation.ActivityResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivityTest.java    From friendspell with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: ResettingStubberImpl.java    From android-test with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: ActivityTestRule.java    From android-test with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: ResettingStubberImplTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: ResettingStubberImplTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: AddNoteScreenTest.java    From androidtestdebug with MIT License 6 votes vote down vote up
@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())));
}
 
Example #7
Source File: AddNoteScreenTest.java    From androidtestdebug with MIT License 6 votes vote down vote up
@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())));
}
 
Example #8
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #9
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #10
Source File: ResettingStubberImplTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #11
Source File: ResettingStubberImplTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #12
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #13
Source File: ResettingStubberImplTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #14
Source File: ResettingStubberImplTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #15
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example #16
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: ActivityResultMatchers.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
  };
}
 
Example #18
Source File: ActivityResultMatchersTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #19
Source File: ActivityResultMatchersTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #20
Source File: IntentTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #21
Source File: ActivityTestRuleTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #22
Source File: ActivityTestRuleTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #23
Source File: IntentStubberRegistryTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  mIntentStubber =
      new IntentStubber() {
        @Override
        public ActivityResult getActivityResultForIntent(Intent intent) {
          return null;
        }
      };
}
 
Example #24
Source File: InstrumentationActivityInvoker.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: SignInActivityTest.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 4 votes vote down vote up
@Override
public ActivityResult apply(Intent intent) {
  wasCalled = true;
  return result;
}
 
Example #27
Source File: IntentsIntegrationTest.java    From android-test with Apache License 2.0 4 votes vote down vote up
private TestActivityResultFunction(ActivityResult result) {
  this.result = result;
}
 
Example #28
Source File: ActivityResultMatchersTest.java    From android-test with Apache License 2.0 4 votes vote down vote up
@Test
public void successHasResultCode() {
  ActivityResult activityResult = new ActivityResult(1, null);
  assertThat(ActivityResultMatchers.hasResultCode(1).matches(activityResult), is(true));
}
 
Example #29
Source File: ActivityResultMatchersTest.java    From android-test with Apache License 2.0 4 votes vote down vote up
@Test
public void failureHasResultCode() {
  ActivityResult activityResult = new ActivityResult(1, null);
  assertThat(ActivityResultMatchers.hasResultCode(2).matches(activityResult), is(false));
}
 
Example #30
Source File: OpenLinkActionTest.java    From android-test with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  Intents.init();
  // Stubbing to block all external intents
  intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null));
}