Skip to content

Commit

Permalink
Set the calling activity in ActivityScenario when run in Robolectric.
Browse files Browse the repository at this point in the history
This change makes sure that when you use ActivityScenario.launchActivityForResult, your Activity under test will have getCallingActivity() and getCallingPackage() not null (set to the package of the test).

This is needed, if your Activity wants to make sure, that it is being called for result.

PiperOrigin-RevId: 582479442
  • Loading branch information
romkal authored and Copybara-Service committed Nov 15, 2023
1 parent d2d6b77 commit 3ff3de4
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions integration_tests/androidx_test/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ android {
namespace 'org.robolectric.integration.axt'

defaultConfig {
testApplicationId 'org.robolectric.integrationtests.axt'
minSdk 19
targetSdk 34
multiDexEnabled true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,27 @@ public void onActivity_runsOnMainLooperThread() {
});
}
}

@Test
public void getCallingActivity_empty() {
try (ActivityScenario<TranscriptActivity> activityScenario =
ActivityScenario.launch(TranscriptActivity.class)) {
activityScenario.onActivity(
activity -> {
assertThat(activity.getCallingActivity()).isNull();
});
}
}

@Test
public void getCallingActivity_isSet() {
try (ActivityScenario<TranscriptActivity> activityScenario =
ActivityScenario.launchActivityForResult(TranscriptActivity.class)) {
activityScenario.onActivity(
activity -> {
assertThat(activity.getCallingActivity().getPackageName())
.isEqualTo("org.robolectric.integrationtests.axt");
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public void startActivity(Intent intent) {
public void startActivityForResult(Intent intent, @Nullable Bundle activityOptions) {
isActivityLaunchedForResult = true;
controller = getInstrumentation().startActivitySyncInternal(intent, activityOptions);
ShadowActivity shadowActivity = Shadow.extract(controller.get());
shadowActivity.setCallingPackage(getInstrumentation().getContext().getPackageName());
}

@Override
Expand Down

0 comments on commit 3ff3de4

Please sign in to comment.