Logo for tanaschita.com

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 XCTest
class 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)
}
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

async/await

concurrency

swift

How to bridge completions handlers to Swift's async/await

Understand Swift continuations to create your own async/await functions.

05 Dec 2022 · 3 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum