How to unit test async/await functions in Swift
Learn how to write unit tests for async/await functions.
16 Dec 2024 · 5 min read
In this article, we'll cover the basics of unit testing async/await functions, showing how to write test cases for functions that may or may not throw errors.
Let's jump in.

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.
Let's look at an example:
import XCTestclass FibonacciSequenceTests: XCTestCase {func testFibonacciSequence() async {let result = await fibonacciSequence(count: 7)XCTAssertEqual([0, 1, 1, 2, 3, 5, 8], result)}}
In this test, the fibonacciSequence(count:) function is asynchronous, so we simply mark the test function with async and use await when calling the function. This eliminates the need for managing expectations or manually waiting for the result.
For async functions that may throw an error, we can handle them using the try keyword.
func testFibonacciSequence() async {let result = try? await fibonacciSequence(count: 7)XCTAssertNotNil(result)XCTAssertEqual([0, 1, 1, 2, 3, 5, 8], result)}
Alternativaly, we can mark our test function with throws:
func testFibonacciSequenceWithErrorHandling() async throws {let result = try await fibonacciSequence(count: 7)XCTAssertEqual(result, [0, 1, 1, 2, 3, 5, 8])}
In this version, if fibonacciSequence(count:) throws an error, the test will automatically fail.
If we need to handle specific error cases, we can also use a do-catch block:
func testFibonacciSequenceThrowsError() async throws {do {let _ = try await fibonacciSequence(count: -1)XCTFail("Expected an error for negative count, but no error was thrown")} catch FibonacciError.invalidCount {// Success! The expected error was thrown.} catch {XCTFail("Unexpected error thrown: \(error)")}}



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



