iosswiftxctestswift-testing

Is there an XCTFail() equivalent in Swift Testing?


I am translating some unit tests from XCTest to Swift Testing, and I am looking for a way to purposefully fail a test, like so:

if let event = SentryManager.events.first, let message = event.message {
  XCTAssertEqual(event.formatted, "hello")
} else {
  XCTFail()
}

This I use mostly when unwrapping values during a test, and so far I haven't found a "fail test" command, which makes translating these unit tests a bit annoying.

Imperfect alternatives:

Using optional unwrapping, like so

#expect(SentryManager.events.first?.message?.formatted == "hello")

results in a comparison between an Optional("hello") and "hello", and will therefore not work.

Force-unwrapping, like so

#expect(SentryManager.events.first!.message!.formatted == "hello")

would fail correctly here if the string we are checking is wrong. I would like to avoid force-unwrapping here though, even though is a unit test and more ok than usual, which would necessitate using some swiftlint ignores, once the linter starts complaining.

Is there a way to purposefully fail a test with the new Swift Testing framework?


Solution

  • Finally, XCTest has a function, XCTFail(), that causes a test to fail immediately and unconditionally. This function is useful when the syntax of the language prevents the use of an XCTAssert() function. To record an unconditional issue using the testing library, use the Issue.record(_:sourceLocation:) function:

    See Migrating a test from XCTest guide in the documentation. There is also an example.