Accessing Composables from UiAutomator

[ad_1]

How can you use UiAutomator in Jetpack Compose apps?

UiAutomator has several ways of accessing UI elements on screen depending on an element type. You can use the By selector class for accessing elements. You can use By.text() to access elements by text label, By.desc() to access by contentDescription, by element flags such as By.scrollable(), By.checkable(), By.clickable(), etc; and By.res() to access an element by its resource-id android:id="@+id/some_id".

First, you need to enable testTagAsResourceId in the composable hierarchy you want to test. This flag will enable converting the testTag to resource identifiers for all nested composables. If you have a single Activity Compose project, you can enable it only once close to the root of the composable tree. This will ensure all of the nested composables with Modifier.testTag are accessible from the UiAutomator.

/* Copyright 2022 Google LLC. 
SPDX-License-Identifier: Apache-2.0 */

Scaffold(
modifier = Modifier.semantics {
testTagsAsResourceId = true
},
// ...
)

/* Copyright 2022 Google LLC. 
SPDX-License-Identifier: Apache-2.0 */

LazyVerticalGrid(
modifier = modifier
.fillMaxSize()
.testTag("forYou:feed"),
// ...
)

/* Copyright 2022 Google LLC. 
SPDX-License-Identifier: Apache-2.0 */

class BaselineProfileGenerator {
@get:Rule
val rule = BaselineProfileRule()

@Test
fun generate() {
rule.collectBaselineProfile(PACKAGE_NAME) {
// This block defines the app's critical user journey.
// Here we are interested in optimizing for app startup.
pressHome()
startActivityAndWait()
}
}
}

/* Copyright 2022 Google LLC. 
SPDX-License-Identifier: Apache-2.0 */

class BaselineProfileGenerator {
@get:Rule
val rule = BaselineProfileRule()

@Test
fun generate() {
rule.collectBaselineProfile(PACKAGE_NAME) {
// This block defines the app's critical user journey.
// Here we are interested in optimizing for app startup.
pressHome()
startActivityAndWait()

// Wait until content is asynchronously loaded.
// We find element with resource-id "forYou:feed", which equals to Modifier.testTag("forYou:feed")
device.wait(Until.hasObject(By.res("forYou:feed")), 5_000)
val feedList = device.findObject(By.res("forYou:feed"))

// Set some margin from the sides to prevent triggering system navigation
feedList.setGestureMargin(device.displayWidth / 5)

// Fling the feed
feedList.fling(Direction.DOWN)
device.waitForIdle()
feedList.fling(Direction.UP)
}
}
}

After reading this article you have seen that enabling UiAutomator interoperability with Jetpack Compose is easy and you can leave the content description for accessibility purposes.

[ad_2]

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *