diff --git a/benchmarks/src/main/java/androidx/test/uiautomator/UiAutomatorHelpers.kt b/benchmarks/src/main/java/androidx/test/uiautomator/UiAutomatorHelpers.kt index 85867b982..766de00e1 100644 --- a/benchmarks/src/main/java/androidx/test/uiautomator/UiAutomatorHelpers.kt +++ b/benchmarks/src/main/java/androidx/test/uiautomator/UiAutomatorHelpers.kt @@ -46,3 +46,15 @@ enum class HasChildrenOp { EXACTLY, AT_MOST, } + +/** + * Waits until an object with [selector] if visible on screen and returns the object. + * If the element is not available in [timeout], throws [AssertionError] + */ +fun UiDevice.waitAndFindObject(selector: BySelector, timeout: Long): UiObject2 { + if (!wait(Until.hasObject(selector), timeout)) { + throw AssertionError("Element not found on screen in ${timeout}ms (selector=$selector)") + } + + return findObject(selector) +} diff --git a/benchmarks/src/main/java/com/google/samples/apps/nowinandroid/foryou/ForYouActions.kt b/benchmarks/src/main/java/com/google/samples/apps/nowinandroid/foryou/ForYouActions.kt index 5e4952fbb..bb21f3d39 100644 --- a/benchmarks/src/main/java/com/google/samples/apps/nowinandroid/foryou/ForYouActions.kt +++ b/benchmarks/src/main/java/com/google/samples/apps/nowinandroid/foryou/ForYouActions.kt @@ -20,6 +20,7 @@ import androidx.benchmark.macro.MacrobenchmarkScope import androidx.test.uiautomator.By import androidx.test.uiautomator.Until import androidx.test.uiautomator.untilHasChildren +import androidx.test.uiautomator.waitAndFindObject import com.google.samples.apps.nowinandroid.flingElementDownUp fun MacrobenchmarkScope.forYouWaitForContent() { @@ -27,7 +28,7 @@ fun MacrobenchmarkScope.forYouWaitForContent() { device.wait(Until.gone(By.res("loadingWheel")), 5_000) // Sometimes, the loading wheel is gone, but the content is not loaded yet // So we'll wait here for topics to be sure - val obj = device.findObject(By.res("forYou:topicSelection")) + val obj = device.waitAndFindObject(By.res("forYou:topicSelection"), 10_000) // Timeout here is quite big, because sometimes data loading takes a long time! obj.wait(untilHasChildren(), 60_000) }