Skip to main content

On This Page

Swift Testing #4: Correr pruebas de forma serial

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

Swift Testing #4: Correr pruebas de forma serial

Swift Testing’s default parallel test execution can lead to failures when using shared static state. XCTest, by contrast, runs tests serially by default, avoiding such conflicts.

Why This Matters

Parallel test execution improves speed but introduces risks with shared state. In Swift Testing, this can cause race conditions when multiple tests modify static variables, leading to unpredictable results and debugging overhead. For example, shared static state in the State class can cause test assertions to fail unless tests are explicitly serialized.

Key Insights

  • “Shared static state in Swift Testing can lead to test failures when executed in parallel.”
  • “Use the @Suite(.serialized) trait to ensure tests run sequentially and avoid race conditions.”

Working Example

class State {
    private static var numbers = [1, 2, 3]
    func add(number: Int) {
        State.numbers.append(number)
    }
    func add(numbers: [Int]) {
        State.numbers.append(contentsOf: numbers)
    }
    func removeLastNumber() -> Int? {
        State.numbers.popLast()
    }
    var count: Int {
        State.numbers.count
    }
}
struct StaticTests {
    let state = State()
    @Test
    func test1() {
        state.add(numbers: [4, 5])
        #expect(state.count == 5)
        #expect(state.removeLastNumber() == 5)
    }
    @Test
    func test2() {
        state.add(numbers: [6, 7])
        #expect(state.count == 6)
        #expect(state.removeLastNumber() == 7)
    }
}
@Suite(.serialized) // Definir explícitamente la Suite
struct StaticTests {
    let state = State()
    @Test
    func test1() {
        state.add(numbers: [4, 5])
        #expect(state.count == 5)
        #expect(state.removeLastNumber() == 5)
    }
    @Test
    func test2() {
        state.add(numbers: [6, 7])
        #expect(state.count == 6)
        #expect(state.removeLastNumber() == 7)
    }
}

Practical Applications

  • Use Case: Shared static state in iOS apps using Swift Testing requires serialized test suites to prevent race conditions.
  • Pitfall: Ignoring shared state in parallel tests can lead to inconsistent test results and false negatives.

References:


Continue reading

Next article

Parameterized Testing in Swift: Enhancing Test Coverage with Arguments

Related Content