xcode Swift XCTestCase默认示例现在在每个测试函数上显示“throws

polkgigr  于 2023-02-25  发布在  Swift
关注(0)|答案(1)|浏览(127)

我是一名经验丰富的iOS开发人员,我注意到了一些以前没有注意到的事情,那就是当您创建一个新的XCTestCase类时,它的示例测试函数末尾都有这个新词“throws”,我想知道为什么(因为我以前从来没有添加过它,我只是去了func testThisThing(),末尾没有“throws”),我想知道这是否是一个新的标准实践?我看了苹果的文档,他们似乎也在他们的例子中使用它...
下面是从Xcode生成的XCTestCase类的样子:

class BasicTests: XCTestCase {

    override func setUpWithError() throws {
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDownWithError() throws {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
    }

    func testExample() throws {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        // Any test you write for XCTest can be annotated as throws and async.
        // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
        // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
    }

    func testPerformanceExample() throws {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

正如你在testExample()和testPerformanceExample()的末尾看到的,它写的是“throws”,为什么这是一个新的练习,它的意思是什么,如果我不包括“throws”,它的意思是什么?
干杯

qyuhtwio

qyuhtwio1#

通过将测试方法声明为throws,可以使用try。这对于XCTUnwrapXCTSkipIf和自定义帮助程序特别有用。
将所有测试方法声明为throws并没有什么损失。不这样做的缺点是,无论何时你想使用try,都必须将它们添加回去。为什么要这么麻烦呢?在任何地方都这样做就行了。
我使用throws作为我的标准测试代码片段。

相关问题