有没有办法让全班跳过 Swift XCTestCase

问题描述 投票:0回答:1

在 Swift XCTestCase 中,我正在寻找一种方法:

  1. 在设置和拆卸期间运行函数,每个类运行一次,可能会引发错误
  2. 如果上述设置抛出错误,则跳过该类中的所有测试函数

我发现跳过测试的一种方法是

throw XCTSkip()
。我可以在测试函数或
func setUpWithError() throws
内执行此操作。但我无法在
class func setUp()
class func tearDown()
内部执行此操作。

这是一个例子:

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
    }
}
swift xctest xctestcase
1个回答
0
投票

您可以捕获

class func setUp()
中的错误,并使用结果使
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()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.