XCTestCase Setup, Teardown and Test Methods
Structuring test classes with setUp/tearDown and naming test methods.
XCTestCase Basics
XCTestCase is the base class for all Swift unit tests. Each method starting with "test" is a test case.
import XCTest
final class MathTests: XCTestCase {
func testAddition() {
XCTAssertEqual(2 + 2, 4)
}
}setUp and tearDown
setUp() runs before each test. tearDown() runs after each test. Use them for shared state initialization and cleanup.
final class UserServiceTests: XCTestCase {
var sut: UserService!
override func setUp() {
super.setUp()
sut = UserService()
}
override func tearDown() {
sut = nil
super.tearDown()
}
}All lessons in this course
- XCTestCase Setup, Teardown and Test Methods
- XCTAssert Family and Throwing Assertions
- Protocol-Based Mocking and Dependency Injection
- Async Tests and Performance Measurement