How to unit test async/await functions in Swift
Learn how to write unit tests for async/await functions.
20 Jul 2021 · 2 min read
With async/await, unit testing asynchronous code in Swift got easier and shorter compared to testing asynchronous code with completion handlers.
We don't need to setup and handle an XCTestExpectation anymore. All we have to do is to mark the test function with async and call await on the async call.
import XCTestclass FibonacciSequenceTests: XCTestCase {func testFibonacciSequence() async {let result = await fibonacciSequence(count: 7)XCTAssertEqual([0, 1, 1, 2, 3, 5, 8], result)}}
Or, if the method can throw an error:
func testFibonacciSequence() async {let result = try? await fibonacciSequence(count: 7)XCTAssertNotNil(result)XCTAssertEqual([0, 1, 1, 2, 3, 5, 8], result)}

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
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips