Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@available attribute does not work with XCTest classes or methods

Tags:

ios

swift

xctest

I'd like a unit test to only run on a given version of iOS or higher but the @available attribute does not seem to work at all with XCTest methods :-(

For example, I am not able to disable the test at all using any variation of the @available keyword. The test always executes regardless of whether @available is defined on class or function, uses unavailable or anything. For example...

// Still runs on iOS
@available(iOS, unavailable)
class SomeTests: XCTestCase {
    func testSomething() {
        print("operatingSystemVersion=\(ProcessInfo.processInfo.operatingSystemVersion)")
        XCTFail()
    }
}
// Still runs on iOS
class SomeTests: XCTestCase {
    @available(iOS, unavailable)
    func testSomething() {
        print("operatingSystemVersion=\(ProcessInfo.processInfo.operatingSystemVersion)")
        XCTFail()
    }
}

I am able to achieve what I want with the below but this isn't really practical for lots of tests, is prone to error, is determined at runtime and the test methods still execute and show as success (which isn't really the case).

class SomeTests: XCTestCase {
    func testSomething() {
        if #available(iOS 10.0, *) {
           print("operatingSystemVersion=\(ProcessInfo.processInfo.operatingSystemVersion)")
           XCTFail()
        }
    }
}

I don't think the preprocessor macro #if os(...) can help because it cannot do version checking.

Is there any other way to achieve what I want? Am I doing something wrong with @available (or maybe this is just a bug)?

like image 925
Oliver Pearmain Avatar asked Jan 08 '20 12:01

Oliver Pearmain


1 Answers

This might be a good candidate for XCTSkip

class SomeTests: XCTestCase {
    func testSomething() throws {
        guard #available(iOS 13.0, *) else {
           throw XCTSkip("Unsupported iOS version")
        }
        /// Run iOS 13+ tests
    }
}

Note that test functions can now be marked throws, and this is necessary to use the XCTSkip API.

like image 119
Jonathan Downing Avatar answered Sep 22 '22 18:09

Jonathan Downing