在 Swift XCTestCase 中,我正在寻找一种方法:
我发现跳过测试的一种方法是
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
}
}
您可以捕获
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()
}
}
}