Test on 50,000+ Real Android and iOS Devices
Live and Automated Real Device Testing on 50,000+ iOS and Android Devices. No Need to Buy or Maintain Device Lab
XCTest Tutorial: Unit, Async, UI and Performance Tests, Then Real iPhones
XCTest guide: write XCTestCase unit tests, async expectations, UI and performance tests, run them with xcodebuild, then on real iPhones in the cloud.
Published on:
XCTest is Apple's testing framework for Xcode projects. You inherit from XCTestCase, name your methods with a 'test' prefix, and use the XCTAssert functions to verify your results. The same framework can be used to run unit, integration, UI and performance tests via Xcode or xcodebuild, and the UI tests can be run on real iPhones in a device cloud.
This guide is for developers and SDETs who already have an iOS app in production and want a test suite that will actually work in CI. For the big picture (simulators, test plans, CI, etc.), see the TestMu AI iOS testing guide.
This tutorial goes into more depth on XCTest specifically. It has a working example of each type of XCTest test, the xcodebuild commands you'll need for the command line, and the DEVICE checklist for getting your UI tests onto real iPhones.
TL;DR
XCTest is Apple's testing framework for Xcode: you subclass XCTestCase, start each test method's name with "test", and check results with XCTAssert functions. It runs unit, integration, UI and performance tests from Xcode or xcodebuild test, and its UI tests can run on real iPhones in TestMu AI's Real Device Cloud.
Swift Unit Testing and Xcode Unit Testing
- XCTestCase: Each test is a method with no arguments whose name starts with "test", inside an
XCTestCasesubclass.setUpandtearDownrun around every method, andXCTAssertEqualorXCTAssertThrowsErrorchecks the result. - Swift Testing: Apple's newer framework for Swift unit testing in Xcode 16 and later, with
@Testfunctions and#expect. It shares a test bundle with XCTest. Minimum Xcode version: 16. UI tests: No. Performance tests: No, so those stay on XCTest. - Test targets: Xcode unit testing starts with a Unit Testing Bundle or UI Testing Bundle from File > New > Target. Test code reaches the app's internal types only when the app module is built with Enable Testability and imported with
@testable import.
XCTest vs XCUITest
- XCUITest: The UI testing part of XCTest. A UI test drives the running app through
XCUIApplicationand accessibility identifiers, while an XCTest unit test calls functions and types directly. UI and performance tests have no Swift Testing equivalent. - XCTestExpectation: The XCTest tool for callback-based async code. Call
fulfill()in the callback and wait with a timeout; setisInvertedto prove something never happened, orexpectedFulfillmentCountfor callbacks that fire more than once.
Running XCTest in CI and on Real iPhones
- xcodebuild test: Runs a scheme against a destination.
-only-testingand-skip-testingtake TestTarget/TestClass/TestMethod, andbuild-for-testingplustest-without-buildingsplit the build and run stages in CI. - XCUI builds on real devices: TestMu AI runs an XCTest UI suite on real iPhones from two .ipa files (the app and the UI test runner) uploaded with type
xcuit-ios. A build takesonly-testingorskip-testing, never both, and neither withxctestplan.
What Is XCTest and What Can It Test?
XCTest is the framework that Xcode uses to build and run tests for the Apple platforms. Apple describes it as a very mature framework that supports unit tests, integration tests, UI tests, and performance tests (Apple: Adding tests to your Xcode project).
XCTest tests fall into four groups:
- Unit tests call one function or type directly and check the result.
- Integration tests use the same APIs but test a much larger subsystem with far fewer stubs.
- UI tests drive the app through its interface using
XCUIApplication(that's the way a user would). That's what most people refer to as XCUITest when talking about the XCTest framework. - Performance tests will run a block of code a number of times and compare the metrics (e.g., time, memory) against a baseline.
Unit and integration tests are the fast layer that you run on every commit. The UI tests are the slow layer that actually proves the app works on a device and are part of a more complete iOS app testing strategy that really benefits from real hardware.
XCTest vs Swift Testing vs XCUITest: Which Should You Use?
Since Xcode 16, new projects come with two testing systems: Swift Testing and XCTest. Apple points out that you can build from the same test target with both and have them co-existing within the same test bundle. The table below shows where each one sits.
| Aspect | XCTest (unit and integration) | Swift Testing | XCUITest (XCTest UI tests) |
|---|---|---|---|
| What it tests | Functions and types, called directly | Functions and types, called directly | The running app, through its UI |
| How you write a test | XCTestCase subclass, methods starting with test | Functions marked @Test, optional @Suite | XCTestCase subclass using XCUIApplication |
| Assertions | XCTAssertEqual, XCTAssertTrue, XCTAssertNil, XCTAssertThrowsError | #expect, #require | Same XCTAssert functions on UI element state |
| Async code | async throws test methods, or expectations | async throws test functions | Waiting on elements, for example waitForExistence |
| Performance tests | Yes, measure APIs | Use XCTest measure; Apple lists performance tests under XCTest | Yes, for example app launch metrics |
| Where it usually runs | Simulator or Mac, every commit | Simulator or Mac, every commit | Simulator in CI, real devices before release |
Pick Swift Testing for your new unit tests if you're on Xcode 16 or later. Stick with XCTest for your existing suites, performance tests and all your UI tests. If you do migrate, then do the unit tests first and leave the UI and performance tests on XCTest.
How Do You Set Up an XCTest Target in Xcode?
New projects can include test targets from the start. For an existing project:
- Choose File > New > Target.
- Type "Test" in the template filter.
- Select the Unit Testing Bundle (for unit and integration tests) or the UI Testing Bundle (for UI tests).
- Click Next, populate the options, and then click Finish.
To get at the internal types from your test code, you build the app module with Enable Testability and import it with @testable import YourApp. Xcode names the targets with a 'Tests' or 'UITests' suffix, which is the target name you then use in your xcodebuild filters.
How Do You Write Your Very First XCTestCase Unit Test?
An XCTest unit test is arranged, acted upon, and then asserted. You create the objects you need, you call the code under test, and then you assert that the result is what you expect.
import XCTest
@testable import ShopApp
final class CartTotalTests: XCTestCase {
// Test data lives in one place so cases are easy to change.
let itemPricesInCents = [1250, 750]
let expectedTotalInCents = 2000
var cart: Cart!
override func setUp() {
super.setUp()
cart = Cart()
}
override func tearDown() {
cart = nil
super.tearDown()
}
func testTotalAddsItemPrices() {
// Arrange
itemPricesInCents.forEach { cart.add(priceInCents: $0) }
// Act
let total = cart.totalInCents
// Assert
XCTAssertEqual(total, expectedTotalInCents)
}
func testEmptyCartTotalIsZero() {
XCTAssertEqual(cart.totalInCents, 0)
}
func testRemovingUnknownItemThrows() {
XCTAssertThrowsError(try cart.remove(itemID: "missing-item"))
}
}Three rules keep these tests reliable:
- Name your methods with a test prefix. The XCTest runner will automatically detect test methods in your XCTestCase subclasses. Apple's rule is that it's a method with no arguments whose name starts with "test".
- One scenario per test. Apple's XCTest guidance is one test per scenario, so a failure is attributable to one thing.
- Clean up per test.
setUpandtearDownrun around every test method. For one-off cleanup within a test,addTeardownBlockregisters the code to run after that method has finished.
Note: Developers and SDETs: once your UI tests pass on the simulator, you can run the same suite on real iPhones without having to manage a device lab at all. Start with TestMu AI Real Device Cloud, which has 50,000+ real iOS and Android devices.
How Do You Test Async Code With XCTest?
XCTest gives you two ways to test async tasks. If your code uses Swift concurrency, then you just mark the test as async throws and await the call:
func testFetchStatusReturnsShipped() async throws {
let orderID = "A-1001"
let client = OrderClient(transport: StubTransport(status: "shipped"))
let status = try await client.fetchStatus(orderID: orderID)
XCTAssertEqual(status, .shipped)
}For callback-based code, use an XCTestExpectation. Create it, call fulfill() when the callback fires, and wait with a timeout:
final class CatalogLoaderTests: XCTestCase {
// Built with a stub so the test is deterministic.
let loader = CatalogLoader(transport: StubTransport())
func testLoaderCallsCompletion() async {
let completionCalled = expectation(description: "completion called")
loader.load { _ in completionCalled.fulfill() }
await fulfillment(of: [completionCalled], timeout: 2, enforceOrder: false)
}
func testNoFailureOnSuccess() {
let failureReported = expectation(description: "failure reported")
failureReported.isInverted = true // the test fails if this is fulfilled
loader.load { result in
if case .failure = result { failureReported.fulfill() }
}
wait(for: [failureReported], timeout: 1)
}
}Use fulfillment(of:timeout:enforceOrder:) in your async tests and wait(for:timeout:) in your sync ones. An inverted expectation (isInverted = true) will indicate that nothing happened within the timeout period (e.g., "no error callback on success").
If a callback is expected to fire more than once, then set expectedFulfillmentCount (Apple's definition of this is "the number of times fulfill() must be called before the expectation is completely fulfilled"). Set assertForOverFulfill to true to make the test fail if fulfill() is called more times than expected.
How Do You Write a Performance Test With measure()?
A performance test will run a block several times and record the metrics. You can use measure to record the elapsed time, or measure(metrics:block:) if you want to record different metrics:
func testCatalogParsingPerformance() {
let catalogData = Fixtures.largeCatalogJSON
measure(metrics: [XCTClockMetric(), XCTMemoryMetric()]) {
_ = try? CatalogParser().parse(catalogData)
}
}Apple's performance test reference includes XCTClockMetric, XCTCPUMetric, XCTMemoryMetric, XCTStorageMetric, XCTOSSignpostMetric, XCTHitchMetric and XCTApplicationLaunchMetric. A baseline is established in Xcode following the first run, and XCTest will report a failure if a result is substantially worse than that baseline. Performance tests must be run on the same hardware as the baseline, as results from different machines are not comparable.
How Do You Write an XCTest UI Test That Will Actually Work on Real Devices?
A UI test launches the app and then interacts with it via the accessibility elements. Give every element you're going to touch an accessibility identifier in the app (in SwiftUI, this would be .accessibilityIdentifier("addToCartButton")), then target that identifier rather than the visible text:
import XCTest
final class CheckoutUITests: XCTestCase {
let app = XCUIApplication()
let addButtonID = "addToCartButton"
let badgeID = "cartBadge"
override func setUp() {
super.setUp()
continueAfterFailure = false // stop at the first failure in UI tests
app.launch() // fresh launch for every test
}
func testAddToCartUpdatesBadge() {
let addButton = app.buttons[addButtonID]
XCTAssertTrue(addButton.waitForExistence(timeout: 10))
addButton.tap()
// Wait for the badge to update instead of reading it immediately.
let badge = app.staticTexts[badgeID]
expectation(for: NSPredicate(format: "label == %@", "1"), evaluatedWith: badge)
waitForExpectations(timeout: 10)
}
}Waiting with waitForExistence(timeout:) rather than fixed sleeps is far more important on real devices where launch and render times will vary from model to model. Identifiers also survive copy changes and localization, whereas visible text won't.
How Do You Run an XCTest From the Command Line?
xcodebuild test will run the tests for any scheme against a destination. The syntax is documented in Apple's Technical Note TN2339 (Apple TN2339). Keep your project values in variables so that the same script will work in CI:
SCHEME="ShopApp"
SIM_NAME="${SIM_NAME:?set the simulator name, for example from xcrun simctl list}"
DEST="platform=iOS Simulator,name=${SIM_NAME},OS=latest"
# Run every test in the scheme
xcodebuild test -scheme "$SCHEME" -destination "$DEST"
# Run one test class (format: TestTarget[/TestClass[/TestMethod]])
xcodebuild test -scheme "$SCHEME" -destination "$DEST" \
-only-testing:ShopAppTests/CartTotalTests
# Run unit tests only by skipping the UI test target
xcodebuild test -scheme "$SCHEME" -destination "$DEST" \
-skip-testing:ShopAppUITests
# Build once, then run without rebuilding (useful for split CI stages)
xcodebuild build-for-testing -scheme "$SCHEME" -destination "$DEST"
xcodebuild test-without-building -scheme "$SCHEME" -destination "$DEST"TN2339 says that build-for-testing writes an .xctestrun file into the derived data folder and that test-without-building can take that file in with -xctestrun; the test bundles have to exist at the paths that are listed in the file. TN2339 is an archived note, so you should check the current xcodebuild man page (man xcodebuild, or this third-party mirror of the xcodebuild man page) for the current behavior.
The current behavior is that if you pass in more than one -destination, xcodebuild will test on those destinations in parallel, and -disable-concurrent-destination-testing will run the full test suite on one destination before moving on to the next. xcodebuild -showdestinations -scheme "$SCHEME" will list the valid destinations.
How Do You Run Your XCTest UI Tests on Real iPhones With TestMu AI?
TestMu AI runs XCTest UI test suites (XCUI) on real iOS devices via a REST API. The typical split is to run your fast unit tests on the simulator in CI and then forward the UI test suite to real devices prior to release. The XCUITest tutorial and the XCUITest quickstart go through the full flow (the short version is):
- Package up the two .ipa files. Build the app and then go to Product > Build For > Testing for the UI test runner. Wrap each .app in a Payload folder and zip that up as a .ipa (as TestMu AI's guide to creating .ipa files for XCUI tests details). Make sure the iOS Deployment Target is the same in the app and the UI test target (the guide to creating the .ipa files for XCUI tests cautions that if this is mismatched, the tests will run on the local machine but not on the actual devices).
- Upload both files to the uploadFramework endpoint with type
xcuit-ios, using the credentials from the env vars, and keep the twolt://URLs from the responses.curl -u "$LT_USERNAME:$LT_ACCESS_KEY" --location --request POST \ 'https://manual-api.lambdatest.com/app/uploadFramework' \ --form "appFile=@${APP_IPA}" --form 'type="xcuit-ios"' # Repeat with TEST_SUITE_IPA for the UI test runner. - Start the build on the XCUI build endpoint. That's where the XCTest-specific bits come in. Just send the classes that are actually going to be on the device and turn on evidence.
curl -u "$LT_USERNAME:$LT_ACCESS_KEY" --location --request POST \ 'https://mobile-api.lambdatest.com/framework/v1/xcui/build' \ --header 'Content-Type: application/json' \ --data "{ \"app\": \"${APP_URL}\", \"testSuite\": \"${TEST_SUITE_URL}\", \"device\": [\"${DEVICE}\"], \"only-testing\": [\"CheckoutUITests\"], \"video\": true, \"devicelog\": true, \"build\": \"${BUILD_NAME}\" }" - Have a look at the results in the TestMu AI Automation dashboard (pass/fail per test, logs, video and device logs).
The filter rules from Filters for XCUI Tests: only-testing and skip-testing take className or className/testName. You can't mix the two, and you can't mix either of them with xctestplan. Add more names to the device array if you want to run the suite across multiple iPhones in parallel.
A Real XCUI Run of These Calls
These are the responses the upload and build calls above return when they send TestMu AI's sample app and XCUITest suite (both downloadable from the XCUITest quickstart) to a real iPhone. DEVICE was iPhone 15-17, the model-and-iOS-version format the quickstart uses, and only-testing named the suite's LambdaUiKitIOSUITests class.
# 1. Upload the app, then the UI test runner (type xcuit-ios)
{"app_id":"lt://APP10160301791794838532943777","name":"proverbial_ios.ipa","type":"xcuit-ios", ...}
{"app_id":"lt://APP101603431794838537511889","name":"proverbial_ios_xcuitest.ipa","type":"xcuit-ios", ...}
# 2. Start the XCUI build with "only-testing": ["LambdaUiKitIOSUITests"]
{"status":["Success"],"buildId":["31243189"],"message":[""]}
# 3. Tests the build ran, one session each (TestMu AI sessions API)
testTextButtonIsClicked iPhone 15 iOS 17.6.1
testopenIfconfigWebSiteOnBrowser iPhone 15 iOS 17.6.1
testopenmfmlWebSiteOnBrowser iPhone 15 iOS 17.6.1
testverifyAppLaunch iPhone 15 iOS 17.6.1The sample suite has a second class, LambdaUiKitIOSUITestsLaunchTests, with a single testLaunch method. A second build with the same two files and no filter ran all five tests, so the class filter did what the filter rules describe. Each test came back as its own session with its own video and device log, which is the evidence the last item of the DEVICE checklist below asks for.
The DEVICE Checklist: Is Your XCTest UI Suite Ready for Real iPhones?
Run this six-point check before you move a UI suite from the simulator to real devices:
- D - Deployment targets are the same in the app and the UI test target.
- E - Elements have accessibility identifiers, and the tests are querying the identifiers, not the visible text.
- V - Verified waits: every engagement and every state check involves a wait. Elements are waited for to exist (with
waitForExistence(timeout:)) and state changes are verified via a predicate expectation. There are no fixed sleeps. - I - Independent tests: each test launches the app in
setUpand does not depend on another test's state. - C - Class filters planned: you know which classes go to devices with
only-testing, and you are not also passingxctestplan. - E - Evidence on:
videoanddevicelogare enabled so a device failure can be diagnosed without a rerun.
What Are the Common XCTest Problems and How Do You Go About Fixing Them?
| Problem | Likely cause | Fix |
|---|---|---|
| Test method never runs | Name does not start with test, or the method takes arguments | Rename to testSomething() with no parameters |
| Cannot see app types in tests | Module not built for testing | Turn on Enable Testability and use @testable import |
| Async test passes, but the callback never ran | Missing expectation or wait | Add an expectation and fulfillment(of:timeout:enforceOrder:) |
| UI test fails only on devices | Fixed sleeps or text-based queries | Use identifiers and waitForExistence(timeout:) |
| Suite runs locally, not on TestMu AI devices | Deployment target mismatch | Align the iOS Deployment Target in both targets |
| Device build rejected with filters | only-testing combined with skip-testing or xctestplan | Use one filter type per build |
Universal links are another common device-only failure (our guide to testing universal links on iOS looks at that scenario).
When a test fails only on a real device, you need to reproduce it by hand on that same model before you change the test. This TestMu AI tutorial shows you how to open an app on a real device in the cloud for live manual testing:
Subscribe to the TestMu AI YouTube channel for more tutorials on testing and automation.
Conclusion
Write fast XCTest unit tests for every commit, keep your UI tests independent and identifier-based, and run that UI suite on real iPhones prior to release. Kick off with TestMu AI's Real Device Cloud and get your first XCUITest suite uploaded via the XCUITest quickstart.
Before the first device build, check your app and UI test target against the DEVICE checklist, then send a single UI test class with only-testing so the first run stays short and easy to read.
Author
Sai Krishna is Director of Engineering at TestMu AI, where he leads agentic AI for quality engineering, building AI agents that autonomously drive mobile and conversational test automation. His current focus is Agent Testing and Model Context Protocol (MCP) support for mobile. He is a core contributor and member of the Appium open-source project and the creator of AppiumTestDistribution and appium-device-farm. With over 14 years of experience including more than 9 years at Thoughtworks as a Principal Consultant, he holds a BSc in Electronics and speaks regularly at TestMu and Appium Conf on Appium, mobile automation, and agentic AI in testing.
Reviewer
Srinivasan Sekar is Director of Engineering at TestMu AI, where he leads engineering and open-source initiatives behind the Selenium and Appium automation grid and owns TestMu AI's MCP Server. A committer to Appium and a contributor to Selenium, WebdriverIO, Taiko, and AppiumTestDistribution, he brings over 15 years of experience in quality engineering and open-source technologies. He is the author of the Apress book 'The MCP Standard: A Developer's Guide to Building Universal AI Tools with the Model Context Protocol,' a Certified Kubernetes and Cloud Native Associate, and an international conference speaker. Before TestMu AI he spent over eight years at Thoughtworks as a Principal Consultant and Quality Architect. Srinivasan holds a B.Tech in Information Technology from Anna University.
FAQs
Did you find this page helpful?
More Related Blogs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests

















