A comprehensive guide to help you get started with Swift Testing. This cheat sheet covers basic syntax, assertions, setup and teardown, parameterized tests, asynchronous testing, performance testing, grouping tests, avoiding redundancies, and a comparison with XCTest.
- Setting Up Swift Tests
- Basic Syntax
- Assertions
- Setup and Teardown
- Parameterized Tests
- Asynchronous Testing
- Performance Testing
- Grouping Tests
- Avoiding Redundancies
- Comparison with XCTest
- Migrating from XCTest to Swift Testing
Create a Swift Test Target:
// Open your project in Xcode.
// Go to File > New > Target.
// Choose "Unit Testing Bundle".
// Name your test target (e.g., MyProjectTests).
Define a Test Suite:
@Suite
struct MyTestSuite {
// Test cases go here
}Define a Test Case:
@Test
func myTestCase() throws {
// Test logic goes here
expect(1 + 1 == 2)
}Basic Assertions:
expect(x == y) // Check for equality
expect(x != y) // Check for inequality
expect(x > y) // Check greater than
expect(x >= y) // Check greater than or equal
expect(x < y) // Check less than
expect(x <= y) // Check less than or equalNil Checks:
expect(x == nil) // Check if nil
expect(x != nil) // Check if not nilBoolean Checks:
expect(condition) // Check if trueSetup before each test:
@Suite
struct MyTestSuite {
init() async throws {
// Setup code
}
@Test
func myTestCase() throws {
// Test logic
}
}Teardown after each test::
@Suite
struct MyTestSuite {
deinit {
// Teardown code
}
@Test
func myTestCase() throws {
// Test logic
}
}Define Parameterized Test:
@ParameterizedTest
@Test
func addition(_ a: Int, _ b: Int, _ expected: Int) {
expect(a + b == expected)
}
// Calling the parameterized test
addition(1, 1, 2)
addition(2, 2, 4):
@Test
func testAsyncFunction() async throws {
let result = try await asyncFunction()
expect(result == expectedValue)
}Using #require for Immediate Assertion Failure:
@Test
func myTestCase() throws {
try #require(x == y)
#expect(z.isEnabled)
}Measure Performance:
@PerformanceTest
func testPerformance() throws {
measure {
// Code to measure
}
}Nested Test Suites:
@Suite
struct ParentSuite {
@Suite
struct ChildSuite {
@Test
func childTest() throws {
expect(true)
}
}
@Test
func parentTest() throws {
expect(true)
}
}Remove Redundant test Prefix:
@Test
func example() throws {
expect(true)
}Supported Functionality:
Use UI automation APIs (e.g., XCUIApplication).
Use performance testing APIs (e.g., XCTMetric).
Continue using Objective-C only tests with XCTest.
Avoid using XCTAssert(...) from Swift Testing tests, use #expect(...) instead.
Recommended Practices:
Share a single unit test target.
Swift Testing tests can coexist with XCTest.
Consolidate similar XCTest cases into parameterized tests.
Migrate XCTest classes with a single test method to a global @Test function.
Remove redundant test prefixes from method names.
