Logo for tanaschita.com

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
}
}
Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
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.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

storekit

testing

swift

ios

Get started with StoreKit Testing in Xcode

Learn how to test in-app purchases locally.

04 Sep 2023 · 4 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum