so I'm a seasoned iOS developer and I noticed something that I didn't notice before which is when you make a new XCTestCase class it's example test functions all has this new word "throws" at the end, and I was just wondering why (because I never added it before, I just went func testThisThing() without the "throws" at the end), and I was wondering if it's now a new standard practise? I looked at the apple docs and they seem to use it in their examples too...
So here is what a generated XCTestCase class looks like when you generate it from Xcode:
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.
}
}
}
As you can see at the end of testExample() and testPerformanceExample() it says "throws". Why is this the new practise and what does it mean, and what does it mean if I don't include "throws"?
Cheers
Declaring a test method as
throwsallows you to usetry. This is especially useful forXCTUnwrap,XCTSkipIf, and custom helpers.There is no penalty for declaring all test methods as
throws. The downside of not doing so is having to add them back in whenever you want totrysomething. Why bother? Just do it everywhere.I use
throwsas my standard test code snippet.