xtest

Mobile Testing

Mobile App Testing Strategies

This course teaches a practical, risk-based approach to testing mobile applications across iOS and Android. You will learn how to think about platform fragmentation, build a sensible device matrix, balance manual and automated testing, and choose the right mix of unit, integration, and UI-level tests for a mobile codebase. The course covers automation frameworks such as Appium, Espresso, and XCUITest, the tradeoffs between real devices, simulators, and emulators, mobile-specific concerns like accessibility, performance, and usability, and how to wire mobile test suites into a continuous integration pipeline. By the end, you will be able to design a mobile testing strategy for a real project, justify your device coverage decisions, and know which kinds of bugs each layer of your test suite is meant to catch.

Intermediate · By the Xtest team · About 32 minutes to read

Introduction

Mobile applications live in a far messier environment than most web applications. A single app has to behave correctly across dozens of operating system versions, hundreds of screen sizes, varying hardware capabilities, flaky cellular networks, interruptions like phone calls and push notifications, and strict app store review processes that leave little room for quick hotfixes. Because of this, a mobile testing strategy cannot simply copy the practices used for web testing; it needs its own thinking about what to test, where to test it, and how often. This course walks through that thinking step by step. We start with the foundations: understanding device and OS fragmentation, deciding what belongs in a device matrix, and building a test pyramid that fits a mobile codebase rather than a web one. From there we move into the concrete tools used to automate mobile tests, the real tradeoffs between testing on physical devices versus simulators and emulators, and the mobile-specific disciplines of accessibility, performance, and usability testing. We close with how to wire all of this into a continuous integration pipeline so that mobile quality is checked on every change rather than once before a release. Whether you are a QA engineer moving from web to mobile, a developer who wants to write better mobile tests, or a team lead designing a testing strategy from scratch, this course gives you a framework for making deliberate, defensible decisions rather than testing by habit.

Foundations of Mobile App Testing Strategy

Why Mobile Testing Needs Its Own Strategy

A mobile app is not just a smaller web app. It runs on devices you do not control, on operating systems you cannot patch, over networks that drop and reconnect, and it gets interrupted constantly by calls, notifications, low battery warnings, and screen locks. A testing strategy for mobile has to account for all of this before a single test is written.

Three forces shape every mobile testing decision:

  • Platform fragmentation: iOS and Android differ in UI conventions, lifecycle behavior, permission models, and release cadence. Within Android alone, manufacturers customize the OS and ship different screen densities and hardware.
  • The app lifecycle: apps move between foreground, background, and killed states, and must preserve or discard state correctly at each transition. A bug that only appears after backgrounding an app for ten minutes is easy to miss if your tests never background the app.
  • Store review and release cycles: unlike a web deploy, a mobile release usually goes through app store review, so regressions are costlier and slower to fix in production. This pushes more testing earlier, before a build is submitted.

Building the Strategy Around Risk

No team can test every OS version, every device, and every network condition for every release. A mobile testing strategy starts by identifying which combinations actually matter for your users and which failures would hurt the most: a payment flow breaking is a different risk than a rarely used settings screen rendering slightly wrong on one tablet size.

This section lays the groundwork that the rest of the course builds on: how to read fragmentation data into a device matrix, how to structure a test pyramid so that expensive UI tests are not your only safety net, and how to prioritize what gets automated first. xtest is a hosted web application for end-to-end testing with AI test agents. Through the xtest app, it can drive iPhone simulators on a Mac with Xcode and Android emulators on a Mac with macOS 12 or later, or an x64 PC, which is one option worth knowing about when you later decide where your automated mobile tests will actually run.

Getting these foundations right early prevents two common failure modes: teams that try to test everything and burn out their automation budget on low-value device combinations, and teams that test too narrowly and get blindsided by a crash that only happens on one popular but older device.

Understanding Platform Fragmentation and Building a Device Matrix

Fragmentation is the single biggest difference between mobile and web testing. On iOS, fragmentation is relatively contained: Apple controls both hardware and OS updates, and most users update quickly, but screen sizes still range from compact phones to large tablets, and OS behavior changes meaningfully between major versions. On Android, fragmentation is much wider: manufacturers skin the OS, delay updates, and ship devices with very different CPUs, RAM, and screen densities, so an app that works well on a current flagship phone can behave very differently on a three-year-old budget device.

A device matrix is the deliberate, documented list of OS versions, screen sizes, and device tiers your team commits to testing before a release. Building one well means starting from evidence rather than guesswork: look at your own app's analytics or crash reporting to see which OS versions and device models your actual users run, rather than assuming everyone has the newest phone. A sensible matrix usually includes the current OS version, the previous major version still in common use, at least one small-screen and one large-screen device, and at least one lower-powered device to catch performance and memory problems that never show up on top-tier hardware.

The matrix should not be static. Revisit it each quarter as your user base shifts and as old OS versions drop below a meaningful share of your traffic. Keep the matrix visible to the whole team so that 'does this work on our supported devices' has a clear, shared answer instead of being decided ad hoc by whoever happens to be testing that day. A documented matrix also gives you a basis for deciding what to test manually, what to automate, and what you can reasonably decide not to support at all.

The Mobile Test Pyramid: Balancing Unit, Integration, and UI Tests

The classic test pyramid applies to mobile apps too, but the proportions matter even more because mobile UI tests are slower and flakier than their web equivalents: they have to launch a simulator or emulator (or a real device), wait for animations, and deal with permission dialogs and network variability. A healthy mobile test suite still puts the largest number of tests at the unit level, testing business logic, data parsing, and view models in isolation without touching the UI at all. These run in seconds and catch the majority of logic bugs cheaply.

Above that sits a smaller layer of integration tests that check how pieces work together: a view model correctly reacting to a network response, a local database correctly persisting and reading back data, or a navigation flow correctly passing data between screens. These are more expensive than unit tests but still do not require a full UI test run.

At the top sits a deliberately small number of end-to-end UI tests that drive the actual app on a simulator, emulator, or real device, tapping through the screens the way a user would. These are the most realistic tests but also the slowest and most prone to flakiness from animations, network timing, and permission prompts, so they are reserved for the handful of critical user journeys, such as sign-up, checkout, or the core feature that defines the app. Treating UI tests as the default place to add new coverage is the single most common way mobile teams end up with a slow, flaky suite that nobody trusts.

Risk-Based Prioritization: Deciding What to Automate First

With limited time and an automation budget that is never infinite, the question is not 'what can we automate' but 'what should we automate first.' Risk-based prioritization answers this by weighing two things for every feature or flow: how likely it is to break, and how bad it would be if it did.

Flows that touch money, authentication, or data loss sit at the top of the list regardless of how often they change, because the cost of a regression there is high. Flows that change frequently, such as a feature still being actively developed, are also strong automation candidates, since manual regression testing on them is repetitive and error-prone. On the other hand, a rarely used settings screen that changes once a year might be perfectly well served by an occasional manual check rather than an automated test that has to be maintained forever.

It also helps to separate what must be automated from what is simply nice to automate. A login flow that every single test run depends on is a strong candidate for a resilient, well-maintained automated test. A one-off visual tweak to a marketing screen probably is not worth the ongoing maintenance cost of an automated UI test.

Writing this prioritization down, even as a simple list ranked high to low, turns testing strategy into something the whole team can discuss and revisit, rather than a set of assumptions that live only in one person's head. Revisit the list whenever a new feature ships or a past incident reveals a gap you did not expect.

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

capabilities = {
    "platformName": "Android",
    "automationName": "UiAutomator2",
    "deviceName": "emulator-5554",
    "app": "/path/to/app-debug.apk",
}

driver = webdriver.Remote("http://localhost:4723", capabilities)

# Locate the login button by its accessibility id and tap it
login_button = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_button")
login_button.click()

# Fill in credentials
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "username_field").send_keys("testuser")
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "password_field").send_keys("testpass")
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "submit_button").click()

# Assert the home screen loaded
home_title = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "home_title")
assert home_title.text == "Welcome back"

driver.quit()

A basic Appium test written in Python that drives an Android emulator through a login flow, demonstrating how a single UI-level test at the top of the test pyramid is structured.

import XCTest

class LoginUITests: XCTestCase {
    func testSuccessfulLogin() {
        let app = XCUIApplication()
        app.launch()

        let usernameField = app.textFields["username_field"]
        usernameField.tap()
        usernameField.typeText("testuser")

        let passwordField = app.secureTextFields["password_field"]
        passwordField.tap()
        passwordField.typeText("testpass")

        app.buttons["submit_button"].tap()

        let homeTitle = app.staticTexts["home_title"]
        XCTAssertTrue(homeTitle.waitForExistence(timeout: 5))
        XCTAssertEqual(homeTitle.label, "Welcome back")
    }
}

An equivalent XCUITest written in Swift that runs the same login flow on an iPhone simulator, showing how the same risk-based flow is covered on the other major mobile platform.

Tips

  • Build your device matrix from real usage data such as crash reports or analytics, not from guessing which devices are most popular.
  • Keep UI tests reserved for the small number of critical journeys identified through risk-based prioritization; push everything else down to unit or integration tests.
  • Revisit your device matrix and automation priority list every quarter, since both your user base and your app change over time.
  • Document why each flow was chosen for automation so the decision survives team turnover and can be re-evaluated later.

Common pitfalls

  • Testing only on the newest OS version and the most powerful devices: this misses the bugs that show up on older OS versions or lower-powered hardware that a meaningful share of real users still have. Fix this by including at least one older OS version and one lower-tier device in your matrix.
  • Putting most of the test suite at the UI level because it feels the most 'real': this produces a slow, flaky suite that is expensive to maintain. Fix this by pushing logic down into unit and integration tests and keeping UI tests limited to a handful of critical flows.
  • Treating the device matrix as a one-time decision made at project kickoff: fragmentation and user behavior shift over time, and an unreviewed matrix quietly goes stale. Fix this by scheduling a recurring review of the matrix alongside release planning.

Test Automation Frameworks and Tools for Mobile

Mobile apps run on two very different operating systems, and the tooling you pick shapes how much of your test suite you can share between them and how much you must duplicate. Broadly, teams choose between cross-platform frameworks, which drive both Android and iOS from one codebase, and platform-native frameworks, which are built and maintained by the platform owner for a single operating system.

Appium is the most widely used cross-platform option. It speaks the WebDriver protocol, so a team that already knows Selenium-style automation can reuse the same mental model, assertion libraries and CI setup, just pointed at a mobile driver instead of a browser driver. Because Appium talks to the app through accessibility and UI-automation layers rather than the app's own source, the same test script can often run against Android and iOS with only minor locator changes.

Espresso (Android) and XCUITest (iOS) sit at the other end of the spectrum. They run in-process with the app, which makes them fast and very stable against timing issues, at the cost of writing and maintaining two separate suites, one per platform, usually in different languages (Kotlin or Java for Espresso, Swift or Objective-C for XCUITest).

A fourth path worth knowing about is plain-English test authoring with an AI test agent, as in xtest: you describe a flow in Test Lab and a test agent carries it out on a phone, with the seven non-Performance test agents working on iPhone simulators and Android emulators through the xtest app. This does not replace Appium, Espresso or XCUITest for low-level, framework-level checks, but it removes the locator-maintenance burden for end-to-end flows described in plain language.

The rest of this section compares these options on setup cost, maintenance burden and execution speed, and gives working code for each.

Appium: One Script, Two Platforms

Appium exposes mobile apps through the WebDriver protocol, which means your test runner issues the same kind of commands (findElement, click, sendKeys) it would against a web page, but against a mobile driver (UiAutomator2 for Android, XCUITest for iOS under the hood). This is why Appium is often the first choice for teams that already have Selenium experience: the client libraries, waits, and assertion patterns transfer almost unchanged.

The practical benefit is code reuse. A login flow, a checkout flow, or a settings-toggle test can usually be written once and pointed at either platform's driver with a small capabilities change (app path, platform name, device name). The practical cost is that Appium adds a layer of indirection: every tap goes through the Appium server, then the platform's own automation framework, then the app. That extra hop makes Appium tests slower per step than native frameworks and more sensitive to timing, so generous explicit waits and element-ready checks matter more here than in native scripts.

Locator strategy also needs more care cross-platform. Accessibility ids, when the app exposes them consistently on both Android and iOS, are the most portable locator; raw XPath built against one platform's view hierarchy rarely survives the move to the other. Teams that invest in a shared accessibility-id naming convention between their Android and iOS codebases get the most value out of a single Appium suite, while teams with wildly different UI trees per platform often end up maintaining near-duplicate Appium scripts anyway, eroding the single-codebase benefit.

Espresso and XCUITest: Native Speed, Native Maintenance

Espresso (Android) and XCUITest (iOS) are maintained by each platform owner and run inside, or directly alongside, the app's own process rather than through an external automation server. That proximity is their main advantage: synchronization with the UI thread is built in, so Espresso tests rarely need the explicit sleeps or polling waits that plague slower, cross-process tools, and the same is largely true of XCUITest on iOS. The result is faster, more deterministic test runs, which matters most for large regression suites run frequently in CI.

The cost is duplication. Espresso tests are written in Kotlin or Java against Android view ids; XCUITest tests are written in Swift or Objective-C against iOS accessibility identifiers. A flow that exists on both platforms needs two independently written and independently maintained tests, doubling the review and upkeep burden for any UI change that touches both apps. Teams with small QA or engineering headcount often find this duplication harder to sustain than Appium's single-but-slower suite, while teams with separate Android and iOS engineering teams often prefer it, since each team can own and run its own suite without coordinating a shared cross-platform codebase or driver version.

A common middle ground is to use native frameworks for fast, low-level unit-adjacent UI checks (does this button exist, does this screen render this text) and reserve a cross-platform tool, or a plain-English approach, for longer end-to-end journeys that must behave identically on both platforms.

const { remote } = require('webdriverio');

async function loginTest() {
  const driver = await remote({
    path: '/wd/hub',
    port: 4723,
    capabilities: {
      platformName: 'Android',
      'appium:automationName': 'UiAutomator2',
      'appium:deviceName': 'emulator-5554',
      'appium:app': '/path/to/app-debug.apk'
    }
  });

  const usernameField = await driver.$('~username-input');
  await usernameField.setValue('testuser@example.com');

  const passwordField = await driver.$('~password-input');
  await passwordField.setValue('correct-horse-battery-staple');

  const loginButton = await driver.$('~login-button');
  await loginButton.click();

  const welcomeText = await driver.$('~welcome-message');
  await welcomeText.waitForDisplayed({ timeout: 5000 });

  await driver.deleteSession();
}

loginTest();

An Appium test written with WebdriverIO that logs into an Android app, using accessibility ids (the '~' prefix) as locators so the same test can be adapted to iOS by changing the capabilities block.

import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import org.junit.Rule
import org.junit.Test

class LoginTest {

    @get:Rule
    val activityRule = ActivityScenarioRule(MainActivity::class.java)

    @Test
    fun loginSucceedsWithValidCredentials() {
        onView(withId(R.id.username_input))
            .perform(typeText("testuser@example.com"), closeSoftKeyboard())

        onView(withId(R.id.password_input))
            .perform(typeText("correct-horse-battery-staple"), closeSoftKeyboard())

        onView(withId(R.id.login_button)).perform(click())

        onView(withId(R.id.welcome_message))
            .check(matches(isDisplayed()))
    }
}

An equivalent login test written natively in Espresso for Android, showing the in-process style: no server, no network hop, and view ids instead of accessibility ids.

Tips

  • Standardize on accessibility ids (or equivalent) in your app's own codebase before writing Appium tests; it is the one locator type that tends to survive both platforms and UI redesigns.
  • Keep native Espresso and XCUITest suites focused on fast, frequent checks, and reserve slower cross-process tools or plain-English flows for the handful of critical end-to-end journeys.
  • Pin your Appium driver and platform automation versions (UiAutomator2, XCUITest) in CI; silent driver upgrades are a common source of flaky failures that look like app bugs.

Common pitfalls

  • Writing Appium locators against raw XPath copied from one platform's view hierarchy and assuming it will work on the other; XPath rarely transfers, while accessibility ids usually do.
  • Treating Espresso and XCUITest suites as interchangeable just because they test 'the same feature'; without deliberate sharing of test data and scenarios between the two codebases, the suites quietly drift apart and stop covering the same behavior.

Real Devices, Simulators, and Emulators

A look at the tradeoffs between testing on real physical devices versus simulators and emulators, covering what each option can and cannot reveal, such as real network conditions, battery behavior, camera and GPS hardware, and how to combine both approaches in a practical strategy.

Mobile-Specific Quality Dimensions: Accessibility, Performance, and Usability

Mobile apps live under constraints that desktop web apps rarely face: a screen the size of a hand, a battery that drains, memory that gets reclaimed by the operating system without warning, and users who often have exactly one chance to figure out your app before they delete it. A mobile test strategy that only checks whether buttons work and forms submit misses the dimensions that decide whether real users keep the app.

Why these three dimensions matter more on mobile

  • Accessibility: a phone screen reader user cannot see a misleading icon-only button the way a sighted desktop user might guess at it from context; touch targets that are too small or unlabeled are a daily barrier, not an edge case.
  • Performance: a web page that loads slowly on a desktop with unlimited memory may load far slower, or crash, on a phone with a few hundred megabytes free and a weak connection.
  • Usability: small screens hide navigation behind hamburger menus and gestures that a first-time user has never seen before; what feels obvious to the team that built the app is often not obvious at all on a 6-inch screen.

Treat each dimension as its own pass over the app, with its own checklist and its own pass/fail criteria, rather than hoping functional test coverage happens to catch them.

Accessibility: Screen Readers and Keyboard-Equivalent Navigation

Mobile accessibility testing has two layers. The first is automated rule-checking: scanning the rendered screen for missing labels, insufficient color contrast, and controls with no accessible name, using the WCAG success criteria as the checklist. The second, and the one automated tools cannot fully replace, is walking the app the way an assistive-technology user actually would: with TalkBack or VoiceOver turned on, or by Tab-equivalent navigation on a device that supports an external keyboard or switch control.

Common pitfalls include icon-only buttons with no accessible label, custom components built from a <div> or a generic view that never reports a role to the accessibility tree, and focus order that jumps around the screen in an order no sighted user would follow visually. A control that looks tappable but reports no name or role is invisible to a screen reader even though it is fully visible on screen.

xtest's Accessibility test agent checks the WCAG 2.0 to 2.2 A and AA rules with axe-core on the live page and then walks it by keyboard, in a reduced form on phones. Whatever tool you use, run the automated rule check first to catch the cheap, obvious issues, then spend the remaining time on a manual pass through the app's critical flows with a screen reader turned on, since automated rules alone cannot tell you whether the reading order actually makes sense.

Performance Under Memory and Battery Constraints

Mobile performance testing is not just "does it load fast"; it is "does it survive the conditions a phone actually runs under". Three conditions worth testing deliberately: low available memory (does the app lose its state when the operating system reclaims memory in the background and the user switches back to it), a throttled or intermittent network (does a slow connection leave the user staring at a spinner with no feedback, or does a dropped connection crash a screen instead of showing a retry), and battery and CPU load over a long session (does the app keep draining resources after the user has stopped interacting with it).

Measure concrete numbers rather than impressions: cold start time to first interactive screen, memory footprint after navigating through the app's main flows, and frame time during a scroll of a long list. A profiling tool built into your mobile platform's development environment can capture memory and CPU graphs while you drive the app through a realistic session, which turns "it feels slow" into a specific screen and a specific allocation spike you can fix.

A frequent pitfall is testing performance only on a new high-end device with the app freshly installed and no other apps running, a condition that never matches a real user's phone. Build a low-memory, low-battery, mid-tier device into your regular test pass, not just a one-time benchmark run.

Usability for First-Time Users on Small Screens

Usability on mobile is about watching someone who has never seen the app try to complete a real task: sign up, find a product, finish a checkout, without being told where to tap. The things that trip people up are rarely functional bugs; they are a submit button hidden below the fold, a gesture (swipe to delete, pull to refresh) that is never hinted at visually, or a multi-step form with no indication of how many steps remain.

A practical technique is the task-based walkthrough: write down a single goal ("find and start a return for an order"), hand the app to someone unfamiliar with it, and note every point of hesitation or wrong tap without giving hints. Do this on an actual small screen size, not just in a scaled-down desktop browser, since spacing and target size problems often only show up at real device dimensions.

xtest's Usability test agent finds where a first-time user gets stuck, and it works on iPhone simulators and Android emulators as well as the web. Whatever runs the walkthrough, the output you want is specific: not "users found it confusing" but "three of five tries stopped at the icon-only share button because nothing nearby explained what it does".

const { chromium } = require('playwright');
const AxeBuilder = require('@axe-core/playwright').default;

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext({
    ...require('playwright').devices['iPhone 13'],
  });
  const page = await context.newPage();
  await page.goto('https://example.com/checkout');

  const results = await new AxeBuilder({ page })
    .withTags(['wcag2a', 'wcag2aa'])
    .analyze();

  console.log(`Accessibility violations found: ${results.violations.length}`);
  results.violations.forEach(v => {
    console.log(`- ${v.id}: ${v.description} (${v.nodes.length} nodes)`);
  });

  await browser.close();
})();

Runs an automated WCAG rule scan against the mobile web viewport of a checkout page using Playwright's device emulation and axe-core, catching missing labels and contrast issues before a manual screen-reader pass.

const wdio = require('webdriverio');

async function measureColdStart(capabilities) {
  const driver = await wdio.remote({ capabilities });

  const start = Date.now();
  await driver.pause(100); // allow splash screen to render
  await driver.$('~main-screen-ready').waitForDisplayed({ timeout: 15000 });
  const coldStartMs = Date.now() - start;

  console.log(`Cold start to interactive: ${coldStartMs}ms`);

  const perfData = await driver.execute('mobile: shell', {
    command: 'dumpsys meminfo com.example.app | grep TOTAL',
  });
  console.log('Memory snapshot:', perfData);

  await driver.deleteSession();
}

measureColdStart({
  platformName: 'Android',
  'appium:deviceName': 'emulator-5554',
  'appium:app': '/path/to/app.apk',
});

Uses Appium (via WebdriverIO) to time cold start to an interactive screen and pull a memory snapshot through a shell command, giving concrete numbers instead of a subjective 'it feels slow'.

Tips

  • Run accessibility rule scans early and often, but budget separate time for a manual screen-reader or keyboard-equivalent walkthrough of the app's critical flows, since automated rules cannot judge reading order or whether a label actually makes sense.
  • Measure performance on a mid-tier, partially full device rather than only on a fresh high-end phone, and track concrete numbers like cold start time and memory footprint rather than relying on impressions.
  • For usability, watch someone unfamiliar with the app attempt a single real task on an actual small screen and write down exactly where they hesitate, rather than asking them afterward what they thought.

Common pitfalls

  • Testing accessibility only with an automated rule checker and skipping the manual screen-reader pass, which misses issues like confusing focus order or labels that are technically present but meaningless out of context.
  • Benchmarking performance only once, on a clean high-end device with nothing else running, which hides the memory and battery problems that show up on a real user's older, busier phone.

Integrating Mobile Tests into CI/CD

Running mobile tests on every commit is harder than running web tests, because a build must first exist as an installable artifact (an APK or AAB for Android, an IPA or simulator .app for iOS), and then a device must be provisioned to run it on. This section walks through turning a manual mobile test suite into an automated pipeline stage that catches regressions before a release is cut.

The pipeline generally has three jobs: build the app, provision a device (emulator or simulator), and run the test suite against the freshly built artifact. Each of these can fail independently, so keeping them as separate, clearly logged stages makes failures easier to diagnose than a single monolithic script.

Speed is the recurring challenge. A full regression suite run serially against one emulator can easily dominate a pipeline's runtime, so most teams shard tests across multiple emulator or simulator instances running in parallel, splitting by test file, by tag, or by historical run time so each shard finishes around the same moment.

Finally, the pipeline has to decide what a failure means for the release. A flaky mobile UI test that fails once in twenty runs should not routinely block a deploy, but a crash or a broken critical flow should. Structuring the gate around severity and retry policy, rather than a single pass or fail bit, keeps mobile quality checks useful without making them a bottleneck.

It is worth noting a limit if you reach for xtest in this context: xtest's own REST API, MCP server and CI script only start runs on its Cloud browser, never on your own computer, so a pipeline cannot use them to drive the iPhone simulators or Android emulators that live inside the xtest app.

Provisioning Emulators and Simulators in CI

Android emulators and iOS simulators behave differently in a CI environment than on a developer's laptop, and most pipeline failures in this area trace back to provisioning rather than to the tests themselves.

For Android, a CI runner needs the Android SDK, a system image matching the API level you test against, and enough virtualization support to boot the emulator quickly; many teams cache the SDK and system image between runs to avoid re-downloading several hundred megabytes on every job. Boot time matters: waiting for the emulator to report that it is fully booted, not just that the process has started, avoids tests running against a half-initialized device.

For iOS, simulators require a macOS runner with Xcode installed, since Apple ships its simulator tooling only for macOS. Listing available simulator runtimes and devices before a run, and pinning the exact device and OS version in the pipeline configuration, prevents a test suite from silently running against the wrong iOS version when Xcode is updated on the runner image.

In both cases, cold starts are the enemy of CI speed. Snapshotting a booted emulator or reusing a warm simulator across the test job, rather than cold-booting for every suite, can cut a meaningful amount of time off each pipeline run, especially when the suite itself runs in only a few minutes.

Sharding Tests and Structuring the Quality Gate

Once an app builds and a device boots reliably, the next bottleneck is wall-clock time for the suite itself. Sharding splits a suite across several emulator or simulator instances that run concurrently, each taking a slice of the total tests, so the pipeline's total duration approaches the slowest shard rather than the sum of every test.

A simple sharding strategy splits by test file count; a more balanced one splits by each test's historical duration, so no shard becomes the long pole. Either way, shards need independent, isolated app state: two shards sharing one emulator instance will produce flaky, hard-to-debug failures from interference between tests.

The second half of this subsection is about what happens after the shards report back. A quality gate that fails the build on any single failing test anywhere in a large suite tends to get bypassed or ignored once it starts blocking releases for unrelated flakiness. A steadier approach treats a test's own retry result, its tag (smoke versus full regression), and its severity as inputs to the gate: a smoke-suite failure blocks the release, while a single flaky assertion in a long-tail regression test opens a ticket instead. Keeping the gate's logic in version control alongside the pipeline, rather than as manual judgment calls, keeps it consistent as the team grows.

name: android-emulator-tests
on: [pull_request]
jobs:
  test:
    runs-on: macos-latest
    strategy:
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - name: Set up JDK
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
      - name: Run instrumented tests on emulator
        uses: reactivecircus/android-emulator-runner@v2
        with:
          api-level: 33
          script: |
            ./gradlew connectedCheck \
              -Pshard.count=4 \
              -Pshard.index=${{ matrix.shard }}

A GitHub Actions workflow that boots an Android emulator and runs one shard of an instrumented Gradle test suite per matrix job, so four shards execute in parallel instead of one long serial run.

#!/usr/bin/env bash
set -euo pipefail

DEVICE="iPhone 15"
RUNTIME="iOS-17-0"

xcrun simctl list devices | grep "$DEVICE" || xcrun simctl create "$DEVICE" "$DEVICE" "$RUNTIME"

xcodebuild test \
  -project MyApp.xcodeproj \
  -scheme MyAppUITests \
  -destination "platform=iOS Simulator,name=$DEVICE,OS=17.0" \
  -only-testing:MyAppUITests/SmokeSuite

A shell script that ensures a specific iOS simulator exists on a macOS CI runner and then runs only the smoke-tagged test suite against it, keeping the quality gate fast on every pull request.

Tips

  • Cache the Android SDK, system images and Gradle dependencies between pipeline runs so provisioning time does not dominate every job.
  • Pin the exact emulator API level and simulator OS version in configuration rather than relying on whatever the CI image happens to ship.
  • Keep a short smoke suite that always blocks the release gate, separate from a longer regression suite that runs on a schedule or reports without blocking.

Common pitfalls

  • Sharing one emulator instance across parallel test shards: it causes state leakage between tests that looks like random flakiness; give each shard its own isolated emulator or simulator instance.
  • Treating every test failure as equally release-blocking: a single flaky assertion then trains the team to ignore the gate entirely, so separate failures by severity and retry outcome before deciding what blocks a release.

Exercises

Exercise 1: Build a Device Matrix and Risk-Based Automation Plan

In this exercise you will build a realistic device matrix and a prioritized automation plan for a sample mobile app of your choosing, real or hypothetical. The goal is to practice the risk-based thinking covered in Section 1 rather than to write any code yet. Start by listing the operating system versions and device types you believe matter for your app's audience, then justify each entry with a reason such as usage share, screen size diversity, or known performance constraints. Next, list the five to ten most important user flows in the app, such as sign-up, checkout, or search, and for each one note how likely it is to break and how costly a failure would be. Use those two factors to rank the flows from highest to lowest automation priority. Finally, write one sentence for each of your top three flows explaining whether it belongs at the unit, integration, or UI level of your test pyramid, and why.

  1. Pick a mobile app, real or hypothetical, and describe its core purpose in two sentences.
  2. List 4 to 6 device and OS combinations you would include in its device matrix, with a one-sentence justification for each.
  3. List the 5 to 10 most important user flows in the app.
  4. For each flow, rate its likelihood of breaking and the cost of a failure as High, Medium, or Low, then rank the flows from highest to lowest automation priority.
  5. For your top three ranked flows, state whether each belongs at the unit, integration, or UI test level and justify the choice in one sentence.

Expected outcome: A written device matrix with justified entries and a ranked list of user flows with test-level assignments, demonstrating the ability to apply risk-based thinking to a mobile testing strategy.

Exercise 2: Write a Cross-Platform Login Test

In this hands-on exercise you will adapt the Appium example from Section 1 to a login flow of your own, either against a sample app or a public demo app available for testing purposes. The exercise is meant to reinforce how a single critical flow, identified as high priority in Exercise 1, gets expressed as an automated UI test. You should install Appium locally, connect it to either an Android emulator or an iOS simulator, and write a test that enters credentials, submits the form, and asserts that the resulting screen shows the expected content. Once your test passes, intentionally break one locator, such as changing an accessibility id, and observe how the test fails, then fix it. This practices both writing a UI test and diagnosing the kind of locator-related failure that is extremely common in mobile automation.

  1. Install Appium and its driver for either Android (UiAutomator2) or iOS (XCUITest) following the official Appium documentation.
  2. Start an Android emulator or iOS simulator and confirm Appium can connect to it.
  3. Write a test script, adapting the Section 1 example, that logs in and asserts a success screen appears.
  4. Run the test and confirm it passes.
  5. Deliberately change one locator in the app's accessibility id or test code so the test fails, observe the failure message, then fix the locator and confirm the test passes again.

Expected outcome: A working automated login test that passes against a real emulator or simulator, plus a clear understanding of how a broken locator surfaces as a test failure.

Quiz

1. Why does mobile app testing require a different strategy than web application testing?

  1. Mobile apps cannot have automated tests written for them at all
  2. Mobile apps face device and OS fragmentation, lifecycle states like backgrounding, and app store review cycles that web apps do not
  3. Mobile apps are always simpler than web apps and need less testing
  4. Mobile operating systems are identical across all manufacturers so fragmentation is not a concern
Show answer

B. Mobile apps face device and OS fragmentation, lifecycle states like backgrounding, and app store review cycles that web apps do not

Mobile apps run across a wide range of devices and OS versions, must correctly handle lifecycle transitions like backgrounding and being killed, and typically go through app store review before release, all of which push testing decisions in different directions than for web apps.

2. What is the main purpose of building a device matrix?

  1. To guarantee that every possible device and OS combination in existence is tested before every release
  2. To document a deliberate, evidence-based list of OS versions and device types the team commits to testing, based on real usage data
  3. To replace the need for any automated testing
  4. To list every device manufactured regardless of whether any users actually have it
Show answer

B. To document a deliberate, evidence-based list of OS versions and device types the team commits to testing, based on real usage data

A device matrix is a practical, evidence-based commitment to a manageable set of OS versions and device types informed by actual usage data, not an attempt to test every device that exists.

3. According to the mobile test pyramid concept covered in this course, where should the majority of tests live?

  1. At the UI level, since it is the most realistic way to test an app
  2. At the unit level, testing business logic and data handling in isolation, with fewer integration tests and only a small number of UI tests
  3. Entirely in manual exploratory testing with no automation
  4. Equally split between unit, integration, and UI tests
Show answer

B. At the unit level, testing business logic and data handling in isolation, with fewer integration tests and only a small number of UI tests

Unit tests are fast and cheap to run and maintain, so they should make up the bulk of the suite, with integration tests above them and only a small number of slower, more fragile UI tests reserved for the most critical flows.

4. What does risk-based prioritization use to decide what to automate first?

  1. Alphabetical order of feature names
  2. The personal preference of whichever engineer is available that week
  3. The likelihood a flow will break and the cost of that failure if it does
  4. Whether a flow is visually appealing
Show answer

C. The likelihood a flow will break and the cost of that failure if it does

Risk-based prioritization ranks flows by weighing how likely they are to break against how costly a failure would be, so that limited automation effort goes toward the flows that matter most, like payments or authentication.

5. In the Appium code example from Section 1, what is the test actually verifying?

  1. That the app compiles without errors
  2. That the login flow correctly submits credentials and navigates to a home screen showing the expected welcome text
  3. That the device's battery lasts a full day
  4. That the app's source code follows a particular style guide
Show answer

B. That the login flow correctly submits credentials and navigates to a home screen showing the expected welcome text

The Appium example locates the login fields, submits credentials, and then asserts that the resulting home screen displays the expected welcome text, which is a typical structure for a critical-flow UI test.

Related docs

All courses