XCTest does not help managing Optionality
Originator: | brian.king | ||
Number: | rdar://30667432 | Date Originated: | 2/22/2017 |
Status: | Open | Resolved: | |
Product: | iOS + SDK | Product Version: | |
Classification: | Reproducible: |
Summary: Managing optionals in XCTest quickly becomes painful. Code like this is unfortunately common: ```swift let string: String? = nil XCTAssertNotNil(string) XCTAssert((string?.lengthOfBytes(using: .utf8))! > 0) ``` Very often, developers use `!` which leads to tests that crash in when tests fail. The root of the problem I think is the behavior of `XCTAssertNotNil` does not help with the unwrapping. If this method returned a discardable T and threw, it would discourage bad usage. I use a wrapper like: ``` struct UnexpectedNilError: Error {} func AssertNotNilAndUnwrap<T>(_ variable: T?, message: String = "Unexpected nil variable", file: StaticString = #file, line: UInt = #line) throws -> T { guard let variable = variable else { XCTFail(message, file: file, line: line) throw UnexpectedNilError() } return variable } ``` I added some more thoughts here: https://www.raizlabs.com/dev/2017/02/xctest-optional-unwrapping Steps to Reproduce: Try to write a unit test that unwraps a bunch of optionals and have it not duplicate a lot of code or use a helper. Expected Results: The API should encourage proper unwrapping and error reporting so once optionality is confirmed, the developer has access to the unwrapped value. Actual Results: Tests usually fill with `?` or `!` to manage unwrapping which can miss failures or cause crashes Version: Xcode 8.3 beta 3 Notes: Configuration: XCTest
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!