Swift Tutorial · Swift Projects · Lesson 28 of 30
Swift Testing
Write tests with the Swift Testing framework: @Test, #expect, #require and parameterized tests.
Swift Testing
Swift Testing (import Testing) is the modern test framework, included with Swift 6 toolchains and Xcode
16 and later. Tests are functions marked @Test; #expect records a failure and continues, #require stops
the test. Arguments run a test once per value. Put tests in a test target and run swift test (or press
Cmd-U in Xcode).
import Testing
func discounted(_ price: Double, percent: Int) -> Double {
price * Double(100 - percent) / 100
}
@Test func appliesDiscount() {
#expect(discounted(100, percent: 20) == 80)
}
@Test(arguments: [0, 50, 100])
func neverNegative(percent: Int) {
#expect(discounted(40, percent: percent) >= 0)
}
@Test func parsesQuantity() throws {
let quantity = try #require(Int("3"))
#expect(quantity == 3)
}
@Test func roundsToCents() {
#expect(discounted(9.99, percent: 10) == 8.99) // fails: floating point gives 8.991
}
Output
✔ Test appliesDiscount() passed after <time> seconds. ✔ Test neverNegative(percent:) with 3 test cases passed after <time> seconds. ✔ Test parsesQuantity() passed after <time> seconds. ✘ Test roundsToCents() recorded an issue at AppTests.swift:22:5: Expectation failed: discounted(9.99, percent: 10) == 8.99 ↳ discounted(9.99, percent: 10) == 8.99 → false ↳ discounted(9.99, percent: 10) → 8.991 ✘ Test roundsToCents() failed after <time> seconds with 1 issue. ✘ Test run with 4 tests in 0 suites failed after <time> seconds with 1 issue.
Run this on your computer — see “Get Started” for setup.
A failed expectation shows the values involved, which is often enough to find the bug without a debugger. XCTest still works and is common in older projects.
Test yourself
What's the difference between #expect and #require?
None#expect records a failure and continues; #require stops the test#require is for async code only#expect only works in XCTest
Show answer
Answer: #expect records a failure and continues; #require stops the test