Quick tip on how to unit test Swift optionals with XCTUnwrap
Learn how to shorten if let and guard statements when unit testing.
06 Mar 2023 · 2 min read
When unit testing optionals in Swift, the first idea on how to do that might be to use if let or guard statements combined with the XCTFail assertion method. For example:
func testMixingSmoothies() throws {let smoothieMaker = SmoothieMaker()guard let bananaSmoothie = smoothieMaker.makeBananaSmoothie() else {XCTFail("bananaSmoothie should not be nil")return}}

Architecture & Design Patterns for iOS
This book is a practical guide to essential architectural principles and design patterns for iOS development. It covers strategies for building maintainable apps with Swift and SwiftUI, including dependency injection, navigation, common patterns, and modularization.
LEARN MORE
The XCTest framework actually provides a more elegant solution.
It provides the XCTUnwrap method which attempts to unwrap the optional and throws an error i.e. the test fails if the optional is nil.
func testMixingSmoothies() throws {let smoothieMaker = SmoothieMaker()let bananaSmoothie = try XCTUnwrap(smoothieMaker.makeBananaSmoothie())}
This approach eliminates the need to write repeating XCTFail descriptions. All we need to do is to mark our test function with throws.

Preparing for a technical iOS job interview
Preparing for a technical iOS Job Interview with over 300 questions & answers. Covering Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, iOS File System, Core Data, Concurrency with async/await, Security, Automated Testing, Dependency Management, AI & Machine Learning and more.
LEARN MORE

Architecture & Design Patterns for iOS
This book is a practical guide to essential architectural principles and design patterns for iOS development. It covers strategies for building maintainable apps with Swift and SwiftUI, including dependency injection, navigation, common patterns, and modularization.
LEARN MORE

Become a sponsor of tanaschita.com
By publishing an article on different iOS topics every week, tanaschita.com is constantly growing in the developer community and may provide a great audience for you as a sponsor.
CLICK TO LEARN MORE
Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



