Controllare l'app da Macrobenchmark (visualizzazioni)

Concetti e implementazione di Jetpack Compose

A differenza della maggior parte dei test dell'interfaccia utente Android, i test Macrobenchmark vengono eseguiti in un processo separato dall'app stessa. Ciò è necessario per attivare operazioni come l'interruzione del processo dell'app e la compilazione dal bytecode DEX al codice macchina.

Puoi gestire lo stato della tua app utilizzando la libreria UIAutomator o altri meccanismi che possono controllare l'app di destinazione dalla procedura di test. Non puoi utilizzare Espresso o ActivityScenario per Macrobenchmark perché prevedono di essere eseguiti in un processo condiviso con l'app.

L'esempio seguente trova un RecyclerView utilizzando il relativo ID risorsa e scorrendo più volte verso il basso:

Kotlin

@Test
fun scrollList() {
    benchmarkRule.measureRepeated(
        // ...
        setupBlock = {
            uiAutomator {
                // Before starting to measure, navigate to the UI to be measured
                startIntent(Intent("$packageName.RECYCLER_VIEW_ACTIVITY"))
            }
        }
    ) {
        uiAutomator {
            val recycler = onElement { className == "androidx.recyclerview.widget.RecyclerView" }
            // Scroll down several times
            repeat(3) { recycler.fling(Direction.DOWN) }
        }

    }
}

Java

@Test
public void scrollList() {
    benchmarkRule.measureRepeated(
        // ...
        /* setupBlock */ scope -> {
            // Before measuring, navigate to the UI to be measured.
            val intent = Intent("$packageName.RECYCLER_VIEW_ACTIVITY")
            scope.startActivityAndWait();
            return Unit.INSTANCE;
        },
        /* measureBlock */ scope -> {
            UiDevice device = scope.getDevice();
            UiObject2 recycler = device.findObject(By.res(scope.getPackageName(), "recycler"));

            // Set gesture margin to avoid triggering gesture navigation
            // with input events from automation.
            recycler.setGestureMargin(device.getDisplayWidth() / 5);

            // Fling the recycler several times.
            for (int i = 0; i < 3; i++) {
                recycler.fling(Direction.DOWN);
            }

            return Unit.INSTANCE;
        }
    );
}

Il benchmark non deve scorrere l'interfaccia utente. Può invece eseguire un'animazione, ad esempio. Inoltre, non è necessario utilizzare UI Automator in modo specifico. Raccoglie metriche sul rendimento finché vengono prodotti frame.

A volte vuoi confrontare parti della tua app che non sono direttamente accessibili dall'esterno. Ad esempio, potrebbe trattarsi di accedere ad Attività interne contrassegnate con exported=false, andare a un Fragment o scorrere via una parte dell'interfaccia utente. I benchmark devono navigare manualmente in queste parti dell'app come un utente.

Per navigare manualmente, modifica il codice all'interno di setupBlock{} in modo che contenga l'effetto che vuoi, ad esempio tocco o scorrimento del pulsante. Il tuo measureBlock{} contiene solo la manipolazione della UI che vuoi effettivamente confrontare:

Kotlin

@Test
fun nonExportedActivityScrollList() {
    benchmarkRule.measureRepeated(
        // ...
        setupBlock = setupBenchmark()
    ) {
        // ...
    }
}

private fun setupBenchmark(): MacrobenchmarkScope.() -> Unit = {
    uiAutomator {
        // Before starting to measure, navigate to the UI to be measured
        startApp(TARGET_PACKAGE)
        // click a button to launch the target activity.
        onElement { textAsString() == "RecyclerView" }.click()
        // wait until the activity is shown
        waitForStableInActiveWindow()
    }
}

Java

@Test
public void scrollList() {
    benchmarkRule.measureRepeated(
        // ...
        /* setupBlock */ scope -> {
            // Before measuring, navigate to the default activity.
            scope.startActivityAndWait();

            // Click a button to launch the target activity.
            // While you use resourceId here to find the button, you can also
            // use accessibility info or button text content.
            UiObject2 launchRecyclerActivity = scope.getDevice().findObject(
                By.res(packageName, "launchRecyclerActivity")
            )
            launchRecyclerActivity.click();

            // Wait until activity is shown.
            scope.getDevice().wait(
                Until.hasObject(By.clazz("$packageName.NonExportedRecyclerActivity")),
                10000L
            )

            return Unit.INSTANCE;
        },
        /* measureBlock */ scope -> {
            // ...
        }
    );
}