Is there a way to skip Swift XCTestCase for the whole class

58 views Asked by At

In a Swift XCTestCase, I'm looking for a way to:

  1. Run function during setup and teardown, once per class that may throw error
  2. Skip all the test functions within that one class if the above setup throws error

I found that one way to skip test is to throw XCTSkip(). I can do this within the test function or within func setUpWithError() throws. But I can't do this inside class func setUp() nor class func tearDown().

Here's an example:

class TestClassOne: XCTestCase {
    override class func setUp() {
        // If this fails, I would like to skip tests 1 and 2 but not 3 and 4
        try settingUpForAllTestsInThisClass() // not allowed: setUp doesn't throw
    }

    override class func tearDown() {
        try tearingDownForAllTestsInThisClass() // not allowed: tearDown doesn't throw
    }

    func test1() {
        // Do something that depends on the one time class setup
    }

    func test2() {
        // Do something that depends on the one time class setup
    }
}

class TestClassTwo: XCTestCase {
    override class func setUp() {
        // If this fails, I would like to skip tests 3 and 4 but not 1 and 2
        try settingUpSomethingElseForAllTestsInThisClass() // not allowed: setUp doesn't throw
    }

    override class func tearDown() {
        try tearingDownSomethingElseForAllTestsInThisClass() // not allowed: tearDown doesn't throw
    }

    func test3() {
        // Do something that depends on the one time class setup
    }

    func test4() {
        // Do something that depends on the one time class setup
    }
}
1

There are 1 answers

1
dalton_c On

You could catch the error in class func setUp() and use the result to fail the test in func setUpWithError():

class TestClassOne: XCTestCase {
    static var setupFailed = false

    override class func setUp() {
        do {
            try settingUpForAllTestsInThisClass()
        } catch {
            setupFailed = true
        }
    }

    override func setUpWithError() throws {
        if Self.setupFailed {
            XCTFail()
        }
    }
}