XCTest
default testing framework, bundled with the Xcode IDE.
Test-Driven Development in Swift (2021)
help
XCTestCase offers methods to run code before each test or all the tests will run, as well as after each test or all the tests did run:
import XCTest
@testable import MyProject
// ⭐️ make a subclass of XCTestCase
class TestsForMyType: XCTestCase {
/* -------- test case life cycle -------- */
// ⭐️ runs before ALL tests
override class func setUp() { ... }
// ⭐️ runs after all tests
override class func tearDown() { ... }
// ⭐️ runs before each test
override func setUpWithError() throws { ... }
// ⭐️ runs after each test
override func tearDownWithError() throws { ... }
/* -------- test cases -------- */
// ⭐️ method name starting with “test”
func testThis() { }
func testThat() { }
// ⭐️ performance test case name starting with “testPerformance”?
func testPerformanceExample() throws {
self.measure {
// code to measure the time of
}
}
}
XCTAssertTrue(true)
XCTAssertFalse(false)
compare the values of types conforming to Comparable:
XCTAssertLessThan(1, 2)
XCTAssertGreaterThan(2, 1)
XCTAssertLessThanOrEqual(2, 2)
XCTAssertGreaterThanOrEqual(2, 1)
XCTAssertNil(nil)
XCTAssertNotNil("this is not nil")
// will fail if user == nil, or firstName !== "John"
XCTAssertEqual(user?.firstName, "John")
// use `XCTUnwrap` instead
let u = try XCTUnwrap(user) // fail if user == nil
XCTAssertEqual(u.firstName, "John") // fail if not equal
XCTAssertThrowsError(try aFunctionThatThrows())
XCTAssertNoThrow(try aFunctionThatThrows())
Last updated
Was this helpful?