Swift Testing - Xcode - Apple Developer
Docs
- GitHub
- Documentation
- WWDC24: Meet Swift Testing | Apple - YouTube
- WWDC24: Go further with Swift Testing | Apple - YouTube
Deep Dives
- Video series: Swift and Tips | Mastering Swift Testing series
- Mastering the Swift Testing Framework | Fatbobman’s Blog
- Swift Testing: Getting Started| Kodeco
Cheat Sheet
withKnownIssues
mark a failing test as known so that it will still pass.- This is helpful for passing CI tests for issues that can’t be fixed right now
Use #require
to unwrap
let unwrapped = try #require(last, "the last value should be 4")
#expect(unwrapped == 4)
Passing in parameters into a test
@Test("Continents mentioned in videos", arguments: [
"A Beach",
"By the Lake",
"Camping in the Woods"
])
func mentionedContinents(videoName: String) async throws {
let videoLibrary = try await VideoLibrary()
let video = try #require(await videoLibrary.video(named: videoName))
#expect(video.mentionedContinents.count <= 3)
}
Passing multiple parameters
arguments
can receive anything conforming to Collection
. Here are a few examples.
// Array of Tuples
@Test(arguments: [(1, 2), (2, 4)])
func double(input: Int, result: Int) {
#expect(input * 2 == result)
}
// Dictionary
@Test(arguments: [
1: 2,
2: 4,
])
func double(input: Int, result: Int) {
#expect(input * 2 == result)
}
// multiple arrays
let input = [1,2]
let result = [2,4]
@Test(arguments: input, result)
func double(input: Int, result: Int) {
#expect(input * 2 == result)
}
// zipped arrays
@Test(arguments: zip(input,result))
func double(input: Int, result: Int) {
#expect(input * 2 == result)
}
Serial vs. Parallel
Swift Testing is parallel by default.
To guarantee that a test suite is run in a particular order use @Suite(.serialized
. By using this, you will guarantee that the tests are run in a particular order. However, your tests will take longer because they cannot be run in parallel.