skip to content

In XCTest, what makes a method in an XCTestCase subclass a test, and when do setUp() and tearDown() run around it?

level: juniorimportance: must knowfreq 72%

answer

  1. naming convention, not an annotation
  2. no parameters, no return value
  3. one test case object per method
  4. instance setup before every test, class setup once
  5. teardown blocks first, last in first out

basics

~20 s

A test is an instance method of an XCTestCase subclass whose name starts with test and that takes no parameters and returns nothing. Instance setUp() runs before every test method and tearDown() after it; the class versions run once per class.

solid answer

~40 s

XCTest finds tests by convention: an instance method of an `XCTestCase` subclass with no parameters, no return value and a name that begins with `test`; it may also be `throws`, `async` or both. Each test method runs in its own test case object. Before every method XCTest calls the instance setup overrides (`setUp() async throws`, then `setUpWithError()`, then `setUp()`); after it, any teardown blocks in last-in, first-out order, then `tearDown()`, `tearDownWithError()` and `tearDown() async throws`. The **class** methods `setUp()` and `tearDown()` run once around the whole class. Teardown runs after a failure but not after a crash, so it cleans up and never prepares the next test.

code

swift · 34 lines
swift
import XCTest

final class ServiceRecordStore {
    private(set) var records: [String] = []
    func add(_ record: String) { records.append(record) }
}

final class ServiceRecordStoreTests: XCTestCase {
    private var store: ServiceRecordStore!

    override class func setUp() {
        super.setUp()
        // Runs once, before any test method in this class.
    }

    override func setUpWithError() throws {
        try super.setUpWithError()
        store = ServiceRecordStore()   // a fresh store before every test
    }

    override func tearDown() {
        store = nil
        super.tearDown()
    }

    func testAddingARecordStoresIt() {
        store.add("Oil change")
        XCTAssertEqual(store.records, ["Oil change"])
    }

    func testNewStoreIsEmpty() {
        XCTAssertTrue(store.records.isEmpty)
    }
}

go deeper

for a junior

Recall the three rules for a test method and that the instance setUp() runs before every test method, not once. Name methods after the behaviour so a failure reads as a sentence.

for a middle

Explain the full order: the three setup variants, the test, teardown blocks in reverse order, then the three teardown variants, plus the class-level pair. Show addTeardownBlock beside the resource it removes.

for a senior

Show you have chased an order-dependent failure: shared singletons, defaults or files that per-test objects do not reset, and cleanup that never ran because a test crashed.

for a principal

Weigh class-level shared fixtures against per-test setup cost: a faster suite against hidden coupling, and a team rule that every test builds or resets the state it touches.

## What XCTest treats as a test XCTest finds tests by **convention**, not by an attribute. A **test method** is an instance method on a subclass of `XCTestCase` that: - takes **no parameters**, - returns **no value**, - has a name that begins with the lowercase word **`test`**. The method may also be marked `throws`, `async` or `async throws`; an error that escapes it is recorded as a test failure. A helper such as `makeCalculator()` is never run as a test, and neither is `testConsumption(trips:)`, because it takes an argument. Xcode's test navigator and reports group results by class name and method name, so a name such as `testAverageConsumptionOfThreeTrips()` explains a red line in a report without anyone opening the file. ## Each test method gets its own test case object `XCTestCase` is the unit XCTest runs. A class's `defaultTestSuite` holds a test case object for each test method, each built around that method's invocation, and the per-instance setup methods run on that object before its method. Two consequences follow: - Stored properties such as `var store: ServiceRecordStore!` are prepared again for every test method; one test method never sees a value another method assigned to its own object. - State that lives **outside** the instance is not reset for you: a singleton, `UserDefaults.standard`, a file on disk, a static property. That is where order dependence between tests comes from, and controlling it is the job of setup and teardown. ## The order around one test method For every test method, XCTest runs this sequence: 1. The instance setup methods you overrode, once each: `setUp() async throws` first, then `setUpWithError()`, then `setUp()`. 2. The test method itself. 3. Any **teardown blocks** registered with `addTeardownBlock(_:)` during setup or the test, in last-in, first-out order. 4. The instance teardown methods: `tearDown()` first, then `tearDownWithError()`, then `tearDown() async throws`. Teardown blocks and teardown methods run whether the test passed or failed, even when `continueAfterFailure` is `false`. They do **not** run if the test crashes, which is why Apple's documentation warns against preparing state for later tests in teardown. | Override | Use it when setup… | |---|---| | `setUp()` | is synchronous and cannot fail | | `setUpWithError()` | is synchronous and may throw; a thrown error is recorded as a failure | | `setUp() async throws` | needs to `await` something | The async setup and teardown variants run on an arbitrary actor unless you mark them `@MainActor`, which matters as soon as setup touches an object isolated to the main actor. ## Class-level setup and teardown `XCTestCase` also has **class methods** named `setUp()` and `tearDown()`. XCTest calls `class func setUp()` once before the class runs any of its test methods or their per-instance setup, and `class func tearDown()` once after every test method, teardown block and instance teardown in the class has finished. Use them for expensive, read-only state shared by the whole class, such as parsing a large fixture file once. You cannot put `XCTAssert` checks in them: assertions need a test case instance, and a class method has none. Instance setup and teardown methods, by contrast, may contain assertions, and XCTest evaluates them as part of each test method's run. ## Teardown blocks beside the code that needs them `addTeardownBlock(_:)` registers cleanup right where a resource is created. A test that writes a temporary export file can delete it on the next line, without a stored property and a matching `tearDown()` override. The block may be `async` and may throw; a thrown error is recorded as a failure. You may register blocks from setup or from the test method, but not from a `tearDown` method or from inside another teardown block. ## Naming that reads in a report Because the method name is the label in the test navigator and in every CI report, treat it as the failure message nobody has to write. Apple's examples name the subject and the behaviour, such as `testEmptyTableRowAndColumnCount()` or `testUnreachableURLAccessThrowsAnError()`. Name the class after what it groups, such as `FuelCalculatorTests` or `ServiceRecordStoreTests`. A name like `test1()` still runs, but a red `test1()` at the end of a long CI log tells a reviewer nothing, while `testAverageConsumptionRoundsToOneDecimal()` tells them where to look before they open a file. ## Common mistakes - Assuming the instance `setUp()` runs once per class; that is the class method. - Preparing the next test's state in `tearDown()`, which XCTest does not call after a crash. - Letting a test depend on a singleton another test mutated, then seeing it fail only when the whole class runs. - Putting an assertion in `class func setUp()` and expecting a failure report. - Calling a helper `verifyConsumption()` and wondering why it never appears in the test navigator.

  • When would you use addTeardownBlock(_:) instead of overriding tearDown()?
    When the cleanup belongs to one test's resource, such as a temporary file. Registering the block right after creating the resource keeps the pair together and runs only for the tests that registered it. XCTest runs registered blocks after the test method ends and before `tearDown()`, in last-in, first-out order; a block may be async and may throw, and a thrown error is recorded as a failure.
  • Does tearDown() run when a test method fails, and when it crashes?
    It runs after a failure, including when `continueAfterFailure` is `false` and the method stopped at its first failed assertion. It does not run when the test crashes, for example on a force unwrap of `nil`: XCTest calls neither teardown blocks nor teardown methods then. So teardown must clean up, never be the thing the next test depends on.
  • Your async setUp() configures an object that is isolated to the main actor. What do you change?
    Mark the async override, or the whole test class, `@MainActor`. Without an actor annotation, XCTest runs `setUp() async throws`, `tearDown() async throws` and async teardown blocks on an arbitrary actor, so code there cannot assume it is on the main actor.

Like a rental desk that hands every driver a freshly prepared car: each test method gets its own test case object set up by setUp(), and nothing the previous driver left in their car carries over, though the shared parking garage, like a singleton, is still whatever the last driver made of it.

  • Instance setUp() runs once before all the tests in the class.
  • Any method in a test class runs as a test if it contains an assertion.
  • A test can rely on state that an earlier test method left in the shared app.
  • tearDown() always runs, so it is a safe place to prepare the next test.
  • Assertions inside the class-level setUp() report failures like any other.