Skip to content

Instantly share code, notes, and snippets.

@AungThiha
Last active December 9, 2023 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AungThiha/2570145242377de3510f5eb042d9a6b1 to your computer and use it in GitHub Desktop.
Save AungThiha/2570145242377de3510f5eb042d9a6b1 to your computer and use it in GitHub Desktop.
Jetpack Compose: Assert Intent Data Consumption in Instrumented Tests

Gists for medium article titled Jetpack Compose: Assert Intent Data Consumption in Instrumented Tests

fun <A : ComponentActivity> createAndroidComposeRule(
startActivityIntent: Intent
): AndroidComposeTestRule<ActivityScenarioRule<A>, A> = AndroidComposeTestRule(
activityRule = ActivityScenarioRule(startActivityIntent),
activityProvider = ::getActivityFromTestRule
)
runAndroidComposeUiTest(
activityLauncher = {
ActivityScenario.launch<YourActivity>(
Intent(ApplicationProvider.getApplicationContext(), YourActivity::class.java)
.putExtra("key", "value"),
Bundle().apply {
putString("key", "value")
}
)
}
) {
// assert composables
}
runAndroidComposeUiTest<YourActivity>(
startActivityIntent = Intent(
ApplicationProvider.getApplicationContext(),
YourActivity::class.java
).putExtra("key", "value")
) {
// assert composables
// example assertion below
// onNodeWithText("hello").assertExists().assertIsDisplayed()
}
@get:Rule
val composeTestRule = createAndroidComposeRule<YourActivity>(
Intent(ApplicationProvider.getApplicationContext(), YourActivity::class.java)
.putExtra("key", "value")
)
@ExperimentalTestApi
fun <A : ComponentActivity> runAndroidComposeUiTest(
activityLauncher: () -> ActivityScenario<A>,
effectContext: CoroutineContext = EmptyCoroutineContext,
block: AndroidComposeUiTest<A>.() -> Unit
) {
var scenario: ActivityScenario<A>? = null
val environment = AndroidComposeUiTestEnvironment(effectContext) {
requireNotNull(scenario) {
"ActivityScenario has not yet been launched, or has already finished. Make sure that " +
"any call to ComposeUiTest.setContent() and AndroidComposeUiTest.getActivity() " +
"is made within the lambda passed to AndroidComposeUiTestEnvironment.runTest()"
}.getActivity()
}
try {
environment.runTest {
scenario = activityLauncher()
block()
}
} finally {
scenario?.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment