Developer guide on Swift Testing for iOS
Learn how use Swift Testing to write automated tests.
01 Jul 2024 · 5 min read
At WWDC 2024, Apple released Swift Testing - a new framework which allows us to write automated tests for iOS applications.
Starting with Xcode 16, Swift Testing is now the default Testing framework when we add a testing target to our iOS project.
Let's directly jump in and look at how test functions look in Swift Testing.

Test functions
An example of a test with Swift Testing looks as follows:
import Testing@testable import ExampleAppstruct ExampleAppTests {@Test func testExample() async throws {...expect(resultName == expectedName)}}
A test function follows these rules:
- the @Test annotation indicates that a function is a test.
- a test function can be a global function or a method in a type
- a test function can be async
- a test function can throw
Expectations
To validate expected conditions, we can use the #expect macro. It accepts ordinary expressions and operators, for example:
#expect(!array.isEmpty)#expect(greeting == "Hello")
Alternatively, we can use the #require macro to throw an error and to stop the test if the condition is false. For example:
try #require(!result.isEmpty)
We can also use the #require macro to unwrap an optional:
let element = try #require(array.first)
Traits
We can add traits to the test, for example to describe a test or to customize how it behaves. For example:
- @Test("An example test") to customize the display name of a test
- @Test(.tags(.critical)) to add a custom tag to the test
- @Test.enabled(if: someCondition)) to conditionally enable or disable a test
- @Test.disabled("Describe why disabled")) to skip a test
- @Test(.timeLimit(.minutes(1))) to add a time limit
Suits
To group related test functions we can use suites. A suite is implicitly created when we wrap test functions for example into a struct:
struct ExampleTests {@Test func test1() async throws {...}@Test func test2() {...}}
With suites, we can use init and deinit functions for setup and teardown logic.
Parameterized testing
Swift Testing supports parameterized tests allowing us to run the same test logic multiple times with different input values:
@Test(arguments: ["a", "b", "c"])func example(input: String) {...}
Migrating from XCTest
Swift Testing tests can coexist with XCTest in a single unit test target. This helps us migrate tests incrementally.
Swift Testing does currently not support Ul automation APls such as XCUIApplication or performance testing APls such as XCMetric.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



