0Pricing
Swift Academy · Lesson

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

  1. XCTestCase Setup, Teardown and Test Methods
  2. XCTAssert Family and Throwing Assertions
  3. Protocol-Based Mocking and Dependency Injection
  4. Async Tests and Performance Measurement
← Back to Swift Academy