tezvyn:

UI Automator: Black-Box UI Testing for Android

AI-drafted, machine-checkedSource: developer.android.comadvanced
UI Automator: Black-Box UI Testing for Android

Think of UI Automator as a robot that tests your app by looking at the screen, not your code. It's for end-to-end tests that cross app boundaries, like interacting with the system Settings. The footgun: tests are powerful but can be slow and brittle.

WHY IT EXISTS: Apps don't live in a vacuum; they interact with the Android OS and other apps. Developers needed a way to test user flows that span multiple applications or system UI, simulating how a real user navigates their device from end to end.

THE MENTAL MODEL: UI Automator is like a robot arm with a camera pointed at the device's screen. It has no knowledge of your app's internal code or architecture. It operates purely from the "outside," finding UI components based on what's visible (text, content description, ID) and performing actions like tapping, swiping, or typing. It tests the final, rendered output.

HOW IT WORKS: UI Automator runs as an instrumented test on a physical device or emulator. It leverages Android's accessibility services to inspect the current screen's view hierarchy. Your test code uses the UI Automator API to query this hierarchy for a specific object (e.g., a button with the text "Login"). Once found, you can command it to perform an action, like click(), and then assert that the resulting UI state is correct.

WHEN TO USE IT: Use UI Automator for true end-to-end (E2E) system tests. Its key strength is cross-app testing. For example, testing a flow where your app launches the camera to take a picture, or opens the Settings app to toggle Wi-Fi, and then verifies the result back in your app. It's for validating critical user journeys from start to finish.

WHEN NOT TO USE IT: Avoid it for tests that can be done within your own app's process. For single-app UI testing, Espresso is generally faster and more reliable because it runs in the same process as your app and can synchronize with UI thread operations. Using UI Automator for simple component tests is overkill and leads to slow, flaky test suites.

ONE CANONICAL EXAMPLE: A test could verify a "Share" feature. The test would launch the app, navigate to a piece of content, tap the "Share" button, and then verify that the Android system's share sheet appears. The test could even select an app from the share sheet and assert that the correct content was passed to it. This flow is impossible to test with a framework confined to a single app.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.