In XCTest, how do XCTUnwrap, XCTAssertThrowsError and XCTSkip behave inside a test method marked throws?
answer
- let the test method throw
- fail and stop instead of crashing
- inspect the error in a closure
- a thrown skip is not a failure
- the autoclosure cannot await
basics
~20 sXCTUnwrap records a failure and throws when its value is nil, so a throwing test stops cleanly instead of crashing. XCTAssertThrowsError fails unless its expression throws and passes the error to a closure. Throwing XCTSkip reports the test as skipped.
solid answer
~40 sMarking a test method `throws` lets XCTest handle errors: one that escapes the method is recorded as a failure. `try XCTUnwrap(entries.first)` returns the value or, on `nil`, records a failure and throws, so the method stops at that line; a force unwrap would crash the test process instead, and teardown would not run. `XCTAssertThrowsError(try parser.parse(text)) { error in … }` fails if the expression does not throw, and its closure checks which error, such as `.malformedLine(2)`. Its expression is a synchronous autoclosure, so an async call needs `do`/`catch` with `XCTFail`. Throwing `XCTSkip`, or calling `try XCTSkipIf(…)` or `try XCTSkipUnless(…)`, stops the test and reports it as skipped. Separately, `continueAfterFailure = false` ends a method at its first failed assertion.
code
swift · 32 linesimport XCTest
enum ServiceLogError: Error, Equatable { case malformedLine(Int) }
struct ServiceEntry { let odometer: Int }
struct ServiceLogParser {
func parse(_ text: String) throws -> [ServiceEntry] {
try text.split(separator: "\n").enumerated().map { index, line in
guard let km = Int(line) else { throw ServiceLogError.malformedLine(index + 1) }
return ServiceEntry(odometer: km)
}
}
}
final class ServiceLogParserTests: XCTestCase {
func testFirstEntryHasOdometerReading() throws {
continueAfterFailure = false
let entries = try ServiceLogParser().parse("15200\n30150")
let first = try XCTUnwrap(entries.first, "parser returned no entries")
XCTAssertEqual(first.odometer, 15200)
}
func testMalformedLineReportsItsNumber() {
XCTAssertThrowsError(try ServiceLogParser().parse("15200\nabc")) { error in
XCTAssertEqual(error as? ServiceLogError, .malformedLine(2))
}
}
func testImportFromSharedFolder() throws {
let folder = ProcessInfo.processInfo.environment["SERVICE_LOG_DIR"]
try XCTSkipIf(folder == nil, "SERVICE_LOG_DIR is not set")
}
}go deeper
Recall that XCTUnwrap fails and throws on nil and that a test method must be marked throws to use it. Know that throwing XCTSkip marks a test skipped.
Explain why a force unwrap crashes the run and skips teardown, how the XCTAssertThrowsError closure checks the error, and why async calls need do and catch instead.
Show review judgment: reject force unwraps and bare error assertions in tests, and require skip messages so unrunnable tests stay visible rather than silently green.
Set the team convention for failure handling in tests: throwing helpers over force unwraps, when continueAfterFailure is turned off, and how skipped tests are tracked so they do not rot.
## Throwing test methods A test method may be declared `throws` (or `async throws`). XCTest then treats an error that escapes the method as a **test failure**. This lets a test call throwing production code with plain `try` instead of wrapping it in `do`/`catch`, and it is what makes `XCTUnwrap` and `XCTSkip` work: both stop a test by throwing. ## XCTUnwrap: fail and stop instead of crashing `XCTUnwrap(_:_:file:line:)` takes an optional expression. If the value is non-`nil`, it returns the unwrapped value; if it is `nil`, it records a failure and throws. Compare the alternatives for the first entry of a parsed service log: - `entries.first!` traps on `nil`. The **test process crashes**, the failure is not reported as an ordinary assertion, and XCTest calls neither teardown blocks nor teardown methods after a crash. - `guard let first = entries.first else { XCTFail(); return }` works but is noisy, and every test repeats it. - `let first = try XCTUnwrap(entries.first, "parser returned no entries")` fails with a message, stops the method, and lets the next test run normally. ## XCTAssertThrowsError and XCTAssertNoThrow `XCTAssertThrowsError(_:_:file:line:_:)` evaluates its expression and records a failure **if it does not throw**. Its trailing closure receives the thrown error, so the test can check *which* error it was: 1. Pass the throwing call as the first argument, written with `try`. 2. In the closure, cast the error and assert on it, for example `XCTAssertEqual(error as? ServiceLogError, .malformedLine(2))`. 3. Without the closure, any error at all satisfies the assertion, which can hide a parser that fails for the wrong reason. `XCTAssertNoThrow` is the opposite check. Both take their expression as a **synchronous autoclosure**: writing `XCTAssertThrowsError(try await loader.load())` does not compile, with the error that an `async` call appears in an autoclosure that does not support concurrency. For async code, use `do { _ = try await …; XCTFail("expected an error") } catch { … }`. ## Skipping with XCTSkip `XCTSkip` is an error type. Throwing it **ceases the current test and marks it as skipped**, which is neither a pass nor a failure in the report. Two helpers cover the Boolean case: - `try XCTSkipIf(condition, "reason")` skips when the condition is `true`. - `try XCTSkipUnless(condition, "reason")` skips when it is `false`. Use them for tests that cannot run in the current environment, such as an import that needs a fixture folder named by an environment variable. A skip with a message is honest; an early `return` makes the test look green. ## continueAfterFailure `continueAfterFailure` is a property of `XCTestCase`, `true` by default: a method keeps running after a failed `XCTAssert` and can report several failures. Setting it to `false` inside a test method ends that method at the first failure, which reduces noise when later checks only make sense if earlier ones passed. It does not stop other test methods, and teardown blocks and teardown methods still run. | Tool | On the bad path | Test reported as | |---|---|---| | `XCTUnwrap` | records a failure and throws | failed | | `XCTAssertThrowsError` | records a failure when nothing is thrown | failed | | `throw XCTSkip(…)` | throws a skip | skipped | | force unwrap `!` | traps | crash, no teardown | | `continueAfterFailure = false` | stops the method at the first failure | failed | ## XCTFail and the rest of the toolbox `XCTFail(_:file:line:)` records a failure unconditionally. It belongs in branches a test should never reach: the end of a `do` block that expected an error, a `default:` case of a `switch` over a result, or a callback that must not fire. Combined with a throwing test method, the pieces divide the work cleanly: - `try` lets unexpected errors fail the test without ceremony; - `XCTUnwrap` turns a missing value into a clear failure; - `XCTAssertThrowsError` and `XCTFail` check the error paths you expect; - `XCTSkip` keeps environment-dependent tests visible as skipped. ## Common mistakes - Force unwrapping in tests "because it is only a test", then losing a whole run's results to one crash. - Calling `XCTAssertThrowsError` without inspecting the error, so a wrong error type still passes. - Writing `return` instead of throwing `XCTSkip`, so an unrunnable test is counted as a pass. - Expecting `XCTUnwrap` to work in a method that is not marked `throws`; the call needs `try` and a throwing context.
- How do you assert that an async throwing function throws a specific error in XCTest?Use `do`/`catch` in an `async` test: `do { _ = try await loader.load(); XCTFail("expected an error") } catch { XCTAssertEqual(error as? ServiceLogError, .malformedLine(2)) }`. `XCTAssertThrowsError` cannot help, because its expression is a synchronous autoclosure and an `await` inside it does not compile.
- When is continueAfterFailure = false worth setting?When later assertions are meaningless once an earlier one fails, such as checking fields of a record whose count was already wrong. Stopping at the first failure keeps the report to the real cause. It affects only the current test method; other methods still run, and teardown still runs.
- Force unwrapping in a test is fine because a crash is just a failure.
- XCTUnwrap returns nil and lets the test continue when the value is missing.
- XCTAssertThrowsError without a closure proves the right error was thrown.
- XCTAssertThrowsError accepts an awaited call in an async test.
- Returning early from a test is the same as skipping it.
- continueAfterFailure = false stops the whole test class at the first failure.