UiAutomator2 Driver

UiAutomator2 Driver is an open-source test automation framework used for automating native, hybrid, and mobile web apps on Android devices and emulators. It leverages Google's UiAutomator framework for UI interaction and testing.

Detailed explanation

UiAutomator2 Driver is a powerful tool for automating Android UI tests. It builds upon Google's UiAutomator framework, providing a more flexible and robust solution for interacting with Android applications. Unlike its predecessor, UiAutomator, UiAutomator2 doesn't require access to the application's source code, making it suitable for testing third-party apps or when the source code isn't available. It also supports running tests on devices with Android API level 16 (Jelly Bean) and above, offering broader compatibility.

Key Features and Advantages:

  • Accessibility: UiAutomator2 leverages the Accessibility APIs provided by Android, allowing it to interact with UI elements regardless of their internal implementation. This makes it resilient to changes in the application's UI structure.
  • Cross-Process Testing: UiAutomator2 can interact with multiple applications and system components during a test, enabling complex scenarios that involve interactions between different parts of the Android system.
  • Synchronization: UiAutomator2 provides mechanisms for synchronizing test execution with the application's UI, ensuring that actions are performed at the right time and avoiding race conditions.
  • Integration with Appium: UiAutomator2 is commonly used as a driver within the Appium framework, providing a unified interface for automating mobile apps on both Android and iOS. This allows testers to write cross-platform tests that can be executed on different mobile operating systems.
  • No Source Code Required: Tests can be written and executed without needing the application's source code.
  • Supports gestures: UiAutomator2 supports a wide range of gestures, including taps, swipes, pinches, and zooms, allowing testers to simulate realistic user interactions.

Practical Implementation:

To use UiAutomator2 Driver, you typically need the following:

  1. Appium Server: Appium acts as a proxy between your test scripts and the Android device or emulator. You need to install and configure Appium server.
  2. Appium Client Libraries: These libraries provide language-specific bindings for interacting with the Appium server. Popular choices include Java, Python, Ruby, and JavaScript.
  3. Android SDK: The Android SDK provides the necessary tools and libraries for interacting with Android devices and emulators.
  4. Android Device or Emulator: You need a physical Android device or an emulator to run your tests.

Example (Python with Appium):

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
 
desired_caps = {
    "platformName": "Android",
    "deviceName": "Android Emulator", # Or the name of your connected device
    "appPackage": "com.android.settings", # Replace with your app's package name
    "appActivity": ".Settings", # Replace with your app's main activity
    "automationName": "UiAutomator2"
}
 
driver = webdriver.Remote("http://localhost:4723", desired_caps)
 
try:
    # Wait for the search button to be visible
    search_button = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((AppiumBy.ID, "com.android.settings:id/search"))
    )
    search_button.click()
 
    # Find the search input field and enter text
    search_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((AppiumBy.ID, "android:id/search_src_text"))
    )
    search_input.send_keys("wifi")
 
    # Wait for the search results to appear
    wifi_result = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((AppiumBy.XPATH, "//android.widget.TextView[@text='Wi-Fi']"))
    )
    wifi_result.click()
 
    print("Test passed!")
 
except Exception as e:
    print(f"Test failed: {e}")
 
finally:
    driver.quit()

Explanation of the code:

  • desired_caps: This dictionary defines the capabilities of the device or emulator you want to test on. Important keys include platformName, deviceName, appPackage, appActivity, and automationName. Setting automationName to UiAutomator2 tells Appium to use the UiAutomator2 driver.
  • webdriver.Remote: This creates a connection to the Appium server running on http://localhost:4723.
  • WebDriverWait: This is used to wait for UI elements to become visible or clickable before interacting with them. This helps to avoid race conditions and ensure that the test is reliable.
  • AppiumBy: This class provides different locators for finding UI elements, such as ID, XPATH, ACCESSIBILITY_ID, and CLASS_NAME.
  • driver.quit(): This closes the connection to the Appium server and releases the resources.

Best Practices:

  • Use Explicit Waits: Avoid using implicit waits, as they can lead to unpredictable test behavior. Explicit waits allow you to specify the exact conditions that must be met before interacting with a UI element.
  • Use Meaningful Locators: Choose locators that are stable and unlikely to change. Accessibility ID is often a good choice, as it's designed to be used by accessibility tools and is less likely to be modified during development. If Accessibility ID is not available, resource-id or xpath can be used, but be mindful of potential changes.
  • Write Modular Tests: Break down your tests into smaller, reusable functions. This makes your tests easier to maintain and debug.
  • Use Page Object Model (POM): The Page Object Model is a design pattern that helps to organize your tests by creating separate classes for each page or screen in your application. This makes your tests more readable and maintainable.
  • Handle Dynamic Content: Be aware of dynamic content, such as dates, times, and randomly generated strings. Use appropriate techniques to handle this content, such as regular expressions or parameterized tests.
  • Test on Multiple Devices and Emulators: Ensure that your tests are running on a variety of devices and emulators to catch device-specific issues.
  • Use a CI/CD Pipeline: Integrate your tests into a CI/CD pipeline to automatically run them whenever code changes are made. This helps to catch regressions early and ensure that your application is always in a testable state.

Common Tools:

  • Appium Inspector: A GUI tool that allows you to inspect the UI hierarchy of your application and generate locators.
  • Android Studio: The official IDE for Android development, which includes tools for debugging and testing your application.
  • uiautomatorviewer: A tool included in the Android SDK that allows you to inspect the UI hierarchy of an Android application. It is useful for identifying UI elements and their properties, which can be used to create locators for your tests.

UiAutomator2 Driver is a valuable tool for automating Android UI tests. By following best practices and using the right tools, you can create robust and reliable tests that help to ensure the quality of your Android applications.

Further reading