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

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

所以我是一名经验丰富的 iOS 开发人员,我注意到一些我以前没有注意到的事情,那就是当你创建一个新的 XCTestCase 类时,它的示例测试函数最后都有这个新词“throws”,我只是想知道为什么(因为我以前从未添加过它,所以我只是去 func testThisThing() 最后没有“抛出”),我想知道它现在是否是一种新的标准做法?我查看了苹果文档,他们似乎也在他们的示例中使用了它……

所以这是从 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”又是什么意思?

干杯

ios swift xcode xctest xctestcase
1个回答
0
投票

将测试方法声明为

throws
允许您使用
try
。这对于
XCTUnwrap
XCTSkipIf
和自定义助手特别有用。

将所有测试方法声明为

throws
不会受到惩罚。不这样做的缺点是每当你想要
try
东西时都必须将它们添加回去。何必呢?

我使用

throws
作为我的标准测试代码片段。你可以自己制作,也可以得到我的:https://qualitycoding.org/code-snippets/

© www.soinside.com 2019 - 2024. All rights reserved.